代码优先迁移说有未决的更改,而没有任何更改

Code-first migrations says there are pending changes while there aren't any

所以我正在尝试在 MVC 操作中 运行 MVC 5 中的 database update

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); 它抛出一个错误:

Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.

但是当我执行 add-migration 时,Up()Down() 是空的(同样在添加此迁移之后,它仍然会抛出该异常)

有什么想法吗?

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

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

启用迁移时,会在新创建的命名空间 Migrations 中创建 class Configuration。这个 class 继承自 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");
 }

就是这样。