不同环境下的实体框架数据迁移 [英] Entity Framework Data Migrations for Different Environments

查看:119
本文介绍了不同环境下的实体框架数据迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

There are some base data specific for Dev/Test/Prod environments.

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

We are using now Entity Framework Migrations for all the environments but do not know how to specify migrations for particular environments in a way that we specify a migration to be executed only on Dev/Test/Prod.

这可以在具有Tag属性的Fluent Migrator中完成.但是实体框架呢?

This could be accomplished in Fluent Migrator with Tag attributes. But what about Entity Framework?

推荐答案

当您说基础数据"时,我假设您的意思是播种每个环境.迁移提供了播种机制.在Seed()中,您可以像在常规代码中一样区分环境.我们喜欢使用Web.config转换设置:

When you say 'base data' I assume you mean Seeding each environment. Migrations provide a seeding mechanism for this. Within the Seed() you can differentiate environments as you would in regular code. We like to use Web.config transform setting:

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" },
        );
    }
}

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

Another option is compiler directives:

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
}

对于自己应用迁移,我们遵循此过程发展.准备好部署到UAT时,我们可以将连接字符串指向UAT并运行迁移,也可以.

As far as applying the migrations themselves, we follow 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.

这篇关于不同环境下的实体框架数据迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆