Entity Framework Data Migrations for Different Environments

ef-migrations entity-framework entity-framework-6

Question

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
2
1/30/2017 11:13:38 AM

Accepted Answer

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.

2
1/30/2017 3:27:24 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow