Entity Framework Data Migrations for Different Environments

元气小坏坏 提交于 2020-01-04 09:09:10

问题


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

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.

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


回答1:


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
}

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.



来源:https://stackoverflow.com/questions/41934490/entity-framework-data-migrations-for-different-environments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!