Entity Framework Code First Migrations: Executing migrations using code, not PowerShell commands

Migrations are cool, but all the documentation only shows how to automatically update the database using the Visual Studio Package Mananager Console, like so:

Update-Database

However, I want my database to be updated through code like some of the older builds of Entity Framework Code First allowed.  Well, I did some digging, and here’s what I came up with.

var migratorConfig = new DbMigrationsConfiguration<NorthwindContext>();
migratorConfig.AutomaticMigrationsEnabled = true;

var dbMigrator = new DbMigrator(migratorConfig);
dbMigrator.Update();

If you’ve enabled migrations for your project using the Package Manager Console, you should have a file called Configuration.cs in your Migrations folder.  You can use this instead of using DbMigrationsConfiguration<>.  So with this setup, you’d have:

var migratorConfig = new ProjectNamespace.Migrations.Configuration();

var dbMigrator = new DbMigrator(migratorConfig);
dbMigrator.Update();

Lastly, you should be aware that the DbMigrator constror creates an instance of your DbContext.  So it’s very easy to create an infinite loop if you try to update the database from your DbContext contructor or from an implementation of IDbContextFactory.Create().  However, this is exactly what I wanted to do, so I just had to add some thread-safe checks around my database migration code:

public static int IsMigrating = 0;
private static void UpdateDatabase()
{
    if (0 == Interlocked.Exchange(ref IsMigrating, 1))
    {
        // Manually creating configuration:
        //var migratorConfig = new DbMigrationsConfiguration<NorthwindContext>();
        //migratorConfig.AutomaticMigrationsEnabled = true;

        // Using configuration defined in project:
        var migratorConfig = new ProjectNamespace.Migrations.Configuration();

        // 3
        //var dbMigrator = new DbMigrator(new Settings());
        var dbMigrator = new DbMigrator(migratorConfig);
        dbMigrator.Update();

        Interlocked.Exchange(ref IsMigrating, 0);
    }
}

3 comments so far

  1. Atle on

    Do you know how the migration knows what migration the database is in? The update can take a target migration, but it does not need a source migration.

  2. Moorthy on

    Do you know how to perform Add-Migration using code.

  3. Minimum Code First Setup on

    […] Entity Framework Code First Migrations: Executing migrations using code, not PowerShell commands. […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: