Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Data Migrations for Different Environments

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?

like image 692
Mori Avatar asked Jun 22 '26 23:06

Mori


1 Answers

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.

like image 134
Steve Greene Avatar answered Jun 26 '26 03:06

Steve Greene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!