所以我试图在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);
会抛出错误:
无法更新数据库以匹配当前模型,因为存在挂起的更改并且已禁用自动迁移。将挂起的模型更改写入基于代码的迁移或启用自动迁移。将DbMigrationsConfiguration.AutomaticMigrationsEnabled设置为true以启用自动迁移。
但当我执行add-migration
时,Up()
和Down()
为空(在添加此迁移后,它仍然会抛出该异常)
有什么想法吗?
我也检查过这个:EF Add-Migration indicates "No pending explicit migrations" but Update-Database complains "..there are pending changes"但名称空间没问题。
答案 0 :(得分:0)
好的,正确的解决方案很简单:
启用迁移时,在新创建的名称空间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");
}
就是这样。