实体框架:添加迁移失败,无法更新数据库

时间:2013-04-10 15:36:09

标签: entity-framework

我一直在项目中使用Entity Framework(5.0)一段时间(VS2012 Express中的ASP.NET MVC)。但是现在,我无法再添加迁移。

PM > Add-Migration -projectName MyProject.DAL TestMigration
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时,我仍然会收到“无法更新..”错误。

修改

我尝试了-force参数,但没有区别。

我的配置类的内容(我在上一次迁移后没有改变任何内容):

    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }

    protected override void Seed(Bekosense.DAL.Context.BekosenseContext context)
    {           
        context.Database.ExecuteSqlCommand(Properties.Resources.TriggerAlertMessageDrop);
        context.Database.ExecuteSqlCommand(Properties.Resources.TriggerAlertMessageCreate); 
        context.Database.ExecuteSqlCommand(Properties.Resources.TriggerAlertMessageSentDrop);
        context.Database.ExecuteSqlCommand(Properties.Resources.TriggerAlertMessageSentCreate); 
        context.Database.ExecuteSqlCommand(Properties.Resources.AddDbUsers);
    }

编辑2 当我在DbContext中评论以下行时,我发现我能够进行添加迁移:

//Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Configuration>());

当我将该行置于活动状态并注释掉配置文件中的所有内容时,它仍然无效。 为什么Database.SetInitializer行会导致这种奇怪的行为?

4 个答案:

答案 0 :(得分:22)

您可以重置实体框架以解决您的问题[但请记住它会将迁移带到默认状态]

注意:在执行以下操作之前进行备份

您需要删除当前状态:

  • 删除项目中的迁移文件夹
  • 删除数据库中的__MigrationHistory表(可能在系统表下)

您将在数据库中找到__MigrationHistory表[在App_Data文件夹下]

然后在程序包管理器控制台中运行以下命令:

Enable-Migrations -EnableAutomaticMigrations -Force

使用或不使用-EnableAutomaticMigrations

最后,你可以运行:

Add-Migration Initial

This may also help you

答案 1 :(得分:4)

永远不要使用automigrations,这在过去给我带来了问题(当迁移数据库时,使用正确的方法从头开始!)

这一行应该在你的global.asax:

Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Configuration>());

而不是你的DbContext!

如果以上内容无效,请提供其他提示:

也许你的应用程序中有多个图层:

Add-Migration 000  -StartupProjectName "NameOfTheProjectInSolutionExplorer" -ConfigurationTypeName "MyConfiguration"  -ConnectionString "theconnectionstring;" -ConnectionProviderName "System.Data.SqlClient" -Verbose

以上是我用于多层应用程序的Add-Migration命令。

更新数据库

也是如此
Update-Database -ConfigurationTypeName "SlaveConfiguration" -StartupProjectName "FacturatieMVCv2.Data" -Verbose -script

答案 2 :(得分:4)

在我的情况下,我遇到了同样的错误,因为我在迁移过程中在构造函数方法上强制在类DbContext上使用ObjectContext.CommandTimeout。

尝试删除它

((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 5000;

答案 3 :(得分:4)

这对我有用:

update-database -targetmigration:"0" -force -verbose
add-migration Initial
update-database
相关问题