Entity Framework 不同环境的数据迁移

Entity Framework Data Migrations for Different Environments

有一些特定于 Dev/Test/Prod 环境的基础数据。

我们现在正在为所有环境使用 Entity Framework 迁移,但不知道如何以我们指定仅在 Dev/Test/Prod 上执行的迁移的方式为特定环境指定迁移。 =11=]

这可以在具有标签属性的 Fluent Migrator 中完成。但是 Entity Framework 呢?

当您说 'base data' 时,我假设您的意思是为每个环境播种。迁移为此提供了 seeding mechanism。在 Seed() 中,您可以像在常规代码中一样区分环境。我们喜欢使用 Web.config 转换设置:

protected override void Seed(BookService.Models.BookServiceContext context)
{
    if (ConfigurationManager.AppSettings["DeployEnvironment"] == "UAT")
    {
        context.Authors.AddOrUpdate(x => x.Id,
            new Author() { Id = 1, Name = "Test User" },
        );
    }
    else if (ConfigurationManager.AppSettings["DeployEnvironment"] == "PROD")
    {
        context.Authors.AddOrUpdate(x => x.Id,
            new Author() { Id = 1, Name = "Production User" },
        );
    }
}

另一个选项是编译器指令:

protected override void Seed(BookService.Models.BookServiceContext context)
{
#if DEBUG
    context.Authors.AddOrUpdate(x => x.Id,
        new Author() { Id = 1, Name = "Test User" },
    );
#else
    context.Authors.AddOrUpdate(x => x.Id,
        new Author() { Id = 1, Name = "Production User" },
    );
#endif
}

就应用迁移本身而言,我们遵循 this process in development. When we are ready to deploy to UAT, we can just point the connection string at UAT and run migrations or we can create a script to update the database. In PROD we do this