Running Entity Framework code first migrations programatically

27th Feb 2013

Entity Framework code first migrations can easily be run programmatically. You can specify a specific migration, or you can just update to the latest migration.

To rollback all migrations (calls the "Down" method on each migration):

var configuration = new Configuration(); 
var migrator = new DbMigrator(configuration);

//Rollback
migrator.Update();

To rollback or update to a specific migration:

var configuration = new Configuration(); 
var migrator = new DbMigrator(configuration);

//Update / rollback to "MigrationName"
migrator.Update("MigrationName");

To update to the latest migration:

var configuration = new Configuration();
var migrator = new DbMigrator(configuration);

//Update database to latest migration
migrator.Update();