Menu

Code First Migrations with Continuous Integration

February 19, 2015 by Christopher Sherman

Entity Framework’s Code First Migrations keeps the database in sync with its underlying data model, and Visual Studio provides a convenient checkbox within the Publish Wizard to execute Code First Migrations when publishing manually. If you use continuous integration to publish from source control, however, you still need a way to run migrations on the database. In this tutorial, I’ll explain how to add a flag that sets off the migration task.

Assuming your project is based on a ASP Dot Net MVC template, you already have a folder named App_Start. In this folder, add a class named SqlClientConfig.cs. Within this class we will add a check that conditionally migrates our database based on a flag in Web.config. The code below assumes your migrations exist in the conventional Migrations folder that Entity Framework creates when you enable migrations.

using System.Configuration;
using System.Data.Entity.Migrations;

namespace YourProjectName.App_Start
{
public class SqlClientConfig
{
public static void EnableCodeFirstMigrations()
{
if (bool.Parse(ConfigurationManager.AppSettings["MigrateDatabaseToLatestVersion"]))
{
var configuration = new Migrations.Configuration();
var migrator = new DbMigrator(configuration);
migrator.Update();
}
}
}
}

Open your Global.asax file and, in the Application_Start method, add a call to the method we created in our SqlClientConfig class.

using YourProjectName.App_Start;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace YourProjectName
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
// Other start methods.

            SqlClientConfig.EnableCodeFirstMigrations();
        }
    }

}

With this framework in place, the workflow I use for migrating my data model to a remote database is as follows:

  1. Set MigrateDatabaseToLatestVersion to true in Web.config.
  2. Push the change to source control.
  3. Verify the database migrated successfully once the automated deployment finishes.
  4. Set MigrateDatabaseToLatestVersion to false in Web.config and push again to avoid unnecessarily re-running the migrations on application start.

Entity Framework ASP Dot Net MVC Optimization