C# 使用实体框架和MYSQL自动创建表(代码优先)

C# 使用实体框架和MYSQL自动创建表(代码优先),c#,mysql,asp.net,C#,Mysql,Asp.net,我写这篇文章是因为我需要ASP.NET核心MVC应用程序的帮助。我正在使用带有标识的实体框架 这是dbcontext类。设置DbSet仅用于测试。在这里,Identity必须自动创建所有表,如AspNetUsers,AspNetRoles,等等,就像它使用Sql Server一样,它被称为 如果我没有错,请先编码 public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { p

我写这篇文章是因为我需要ASP.NET核心MVC应用程序的帮助。我正在使用带有标识的实体框架

这是
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);
        }
    }

我希望我的解释正确,并提供了解决此问题所需的所有类。

ApplicationDbContext
类中,确保将所有需要的类添加为公共属性,如
设置

public DbSet<PeopleDataModel> People { get; set; }
public DbSet-People{get;set;}

之后,您需要运行
addmigration AddPeople
命令,该命令将创建一个具有新更改的新迁移类,然后运行
updatedatabase
命令将挂起的迁移应用到数据库。

是否运行了Database Update命令?@waelabas您在说什么命令?
updatedatabase
将挂起的迁移应用到数据库以将挂起的迁移应用到数据库。是的,我使用了它。我迁移了数据库并更新了它。标识表是创建的,现在的问题是,当我想用dbset创建新的dbcontext时,它永远不会被创建。我使用mContext.Database.recreated();但我不创建新表
    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();
    }
public DbSet<PeopleDataModel> People { get; set; }