我写这篇文章是因为我需要有关 ASP.NET Core MVC 应用程序的帮助。我正在使用具有身份的 Entity Framework
这是dbcontext
类。设置DbSet
仅用于测试。这里 Identity 必须自动创建所有表,例如 AspNetUsers
、AspNetRoles
等,就像使用 Sql Server 一样,称为
代码优先如果我没记错的话。
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<SettingsDataModel> Settings { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Fluent API
modelBuilder.Entity<SettingsDataModel>().HasIndex(a => a.Name);
}
}
因此,我创建了数据库类,ASP.NET 应用程序在此处初始化数据库:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySQL(IoCContainer.Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
在启动类(class)中。请注意,我使用 MySql 是因为我将在 Google Cloud Platform 上的 App Engine 中托管应用程序,这就是代码具有 .UseMySQL 的原因。
在 HomeController
中,我执行 EnsureCreated 方法。
protected ApplicationDbContext mContext;
protected UserManager<ApplicationUser> mUserManager;
protected SignInManager<ApplicationUser> mSignInManager;
public HomeController(
ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager)
{
mContext = context;
mUserManager = userManager;
mSignInManager = signInManager;
}
public IActionResult Index()
{
mContext.Database.EnsureCreated(); //<-- It returns false
if (!mContext.Settings.Any()) //<-- Here it throws an exception saying that the database no exists
{
mContext.Settings.Add(new SettingsDataModel
{
Name = "BackgroundColor",
Value = "Red"
});
mContext.SaveChanges();
}
return View();
}
我希望我的解释正确,并且我提供了解决问题所需的所有类。
最佳答案
在您的 ApplicationDbContext
类中,确保将所有需要的类添加为公共(public)属性,例如 Settings
表。
public DbSet<PeopleDataModel> People { get; set; }
之后,您需要运行 Add-Migration AddPeople
命令来创建包含新更改的新迁移类,然后运行 Update-Database
命令来应用挂起的迁移到数据库。
关于c# - 使用 Entity Framework 和 MYSQL 自动创建表(代码优先),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49824816/