【问题标题】:Auto create tables (Code first) using Entity Framework WITH MYSQL使用带有 MYSQL 的实体框架自动创建表(代码优先)
【发布时间】:2018-04-13 20:39:44
【问题描述】:

我写这篇文章是因为我在 ASP.NET Core MVC 应用程序方面需要帮助。我正在使用带有身份的实体框架

这是dbcontext 类。设置DbSet 仅用于测试。在这里,Identity 必须自动创建所有表,例如 AspNetUsersAspNetRoles 等,就像使用 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();

Startup 类中。注意我使用 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();
    }

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

【问题讨论】:

  • 你运行数据库更新命令了吗?
  • @WaelAbbas 你在说什么命令?
  • Update-Database 将挂起的迁移应用到数据库
  • Check this answer 用于将挂起的迁移应用到数据库。
  • 是的,我用过。我迁移了数据库并更新了它。创建了标识表,现在的问题是当我想用 DbSets 创建新的 DbContexts 时,它永远不会被创建。我使用 mContext.Database.EnsureCreated();但我没有创建新表

标签: c# mysql asp.net


【解决方案1】:

在您的 ApplicationDbContext 类中,确保将所有需要的类添加为公共属性,例如 Settings Table。

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

之后,您需要运行Add-Migration AddPeople 命令来创建一个具有新更改的新迁移类,然后运行Update-Database 命令将待处理的迁移应用到数据库。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-11
    • 2012-12-30
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多