代码之家  ›  专栏  ›  技术社区  ›  Matthias Burger

代码优先迁移表示有挂起的更改,而没有

  •  0
  • Matthias Burger  · 技术社区  · 7 年前

    所以我想运行 database update 在MVC 5中,在MVC操作中:

    public async Task<ActionResult> UpdateDatabase(UpdateDatabaseModel updateDatabaseModel)
    {
        DbMigrationsConfiguration migrationsConfiguration = new DbMigrationsConfiguration
        {
            TargetDatabase = new DbConnectionInfo("DefaultConnection"),
            ContextType = typeof(ApplicationDbContext),
            MigrationsAssembly = typeof(ApplicationDbContext).Assembly
        };
    
        var migrator = new DbMigrator(migrationsConfiguration);
        migrator.Update(updateDatabaseModel.SelectedMigration);
        return this.View("ManageApplication");
     }
    

    问题是,在 migrator.Update(updateDatabaseModel.SelectedMigration); 它抛出一个错误:

    无法更新数据库以匹配当前模型,因为存在挂起的更改,并且禁用了自动迁移。将挂起的模型更改写入基于代码的迁移或启用自动迁移。将DBMigrationsConfiguration.AutomaticMigrationsEnabled设置为true以启用自动迁移。

    但当我做一个 add-migration , the Up() Down() 是空的(在添加此迁移之后,它仍然抛出该异常)

    知道吗?

    我也检查过这个: EF Add-Migration indicates "No pending explicit migrations" but Update-Database complains "..there are pending changes" 但是名称空间没问题。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Matthias Burger    7 年前

    好吧,正确的解决方案很简单:

    启用迁移时,在新创建的命名空间中 Migrations 班级 Configuration 是创建的。此类继承自 DbMigrationsConfiguration<TContext> 这个继承自 DbMigrationsConfiguration . 所以,我们不需要创建 new DbMigrationsConfiguration() 但随着它的产生 new Configuration() .

    正确的代码是:

    public async Task<ActionResult> UpdateDatabase(UpdateDatabaseModel updateDatabaseModel)
    {
        DbMigrationsConfiguration configuration = new Configuration();
    
        var migrator = new DbMigrator(migrationsConfiguration);
        migrator.Update(updateDatabaseModel.SelectedMigration);
        return this.View("ManageApplication");
     }
    

    就这样。