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

Eri*_*123 9 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.
Run Code Online (Sandbox Code Playgroud)

我不知道这是否提供任何线索,但"无法..."文本显示为红色.

我试图启用自动迁移(这是没有意义的,因为我正在尝试将挂起的模型更改写入基于代码的迁移)并导致数据库中所需的迁移.然而,这不是我想要的,因为我在项目中没有迁移.

我试图删除数据库并重新创建数据库.重新创建数据库(直到上一次迁移),但是当我尝试使用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);
    }
Run Code Online (Sandbox Code Playgroud)

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

//Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Configuration>());
Run Code Online (Sandbox Code Playgroud)

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

Swa*_*ule 22

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

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

您需要删除当前状态:

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

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

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

Enable-Migrations -EnableAutomaticMigrations -Force
Run Code Online (Sandbox Code Playgroud)

使用或不使用-EnableAutomaticMigrations

最后,你可以运行:

Add-Migration Initial
Run Code Online (Sandbox Code Playgroud)

这也可以帮到你


Nic*_*icy 4

切勿使用自动迁移,这在过去给我带来了问题(向下迁移数据库时,从一开始就使用正确的方法!)

此行应该位于您的 global.asax 中:

Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Configuration>());
Run Code Online (Sandbox Code Playgroud)

而不是在您的 DbContext 中!

如果上述内容没有帮助,其他提示:

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

Add-Migration 000  -StartupProjectName "NameOfTheProjectInSolutionExplorer" -ConfigurationTypeName "MyConfiguration"  -ConnectionString "theconnectionstring;" -ConnectionProviderName "System.Data.SqlClient" -Verbose
Run Code Online (Sandbox Code Playgroud)

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

数据库更新也是如此

Update-Database -ConfigurationTypeName "SlaveConfiguration" -StartupProjectName "FacturatieMVCv2.Data" -Verbose -script
Run Code Online (Sandbox Code Playgroud)