在现有数据库上启用EF6数据库迁移

时间:2019-12-18 22:16:03

标签: entity-framework-6 data-migration entity-framework-migrations

我有一个应用,它背后有一个数据库。此应用程序部署在多个实例中,其中每个实例具有不同版本的代码和数据库。通过不同的版本,我的意思是它可能是代码和数据库的稍旧版本。

我想做的是:

  1. 开始在开发版本上使用EF6数据库迁移。
  2. 以正确的顺序(dev-> stage-> prod),将开发版本部署到其他实例,并使用EF6数据库迁移来更新数据库。
  3. 使用EF6数据库迁移创建新的应用程序实例。

我遇到的问题是:

我知道我可以在开发实例上启用迁移,然后执行Add-Migration Initial –IgnoreChanges并为新的数据库更改创建增量迁移。随着其他环境的更新,将应用这些更改(在部署过程中运行Update-Database)。

但是,我的问题是,使用这种设置,当我不得不启动新的应用程序实例时如何处理?我需要一个迁移来创建所有表。我也知道如何创建此迁移:通过将连接字符串指向空数据库并运行Add-Migration。但是,当我将代码部署到现有实例并运行Update-Database时,EF将尝试运行此基准迁移并崩溃。

如何以简单,自动化的方式处理这两种情况?

我想我正在想象两种类型的迁移:

  • 更新数据库-基线和增量

  • 更新数据库-增量

此外,这将全部自动化,因此我不想运行Update-Database并传递非基准迁移名称以在部署期间在现有数据库上运行。

1 个答案:

答案 0 :(得分:0)

第一

在您的DbContext构造函数中添加

Database.SetInitializer(new CreateDatabaseIfNotExists<MPContext>()); //Create database if not existed
Database.SetInitializer(new MigrateDatabaseToLatestVersion<yourContext, Configuration>()); // uses the configuration for migrations for this DbContext

,您的配置类应如下所示:

internal sealed class Configuration : DbMigrationsConfiguration<DBO.MPContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true; 
        AutomaticMigrationDataLossAllowed = true; 
    }      
}

AutomaticMigrationsEnabled = true;  // enables automatic migrations 
AutomaticMigrationDataLossAllowed = true; 
//this kinda gives permision to delete a table, what I mean is say you have a one to 
//many relation in a table and you decide to remove it for any reason by adding this 
//code you allow the migration to delete the reference (Sorry for the bad english) 

 public class TEST{

   public List<TEST2> test2 {get;set;}
  }

如果您决定从测试中删除测试,则会从TEST类中删除引用(因此丢失了数据)

P.S,如果您使用的是在线数据库,则可能需要在连接字符串中添加Persist Security Info=True

希望这会有所帮助