Entity Framework, Technical

Running Entity Framework code first migrations programatically

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();

Entity Framework, Technical

Seed data from SQL scripts using Entity Framework Migrations (EF 4.3 +)

Normally you would add seed data using native C#.

You can also execute arbitrary SQL statements. To do so, in your Seed method (which can be overriden from your Migration folder in your Configuration class), simply read the contents of any SQL files you want to execute, and tell the context to run them:

internal sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
 {

protected override void Seed(MyDbContext context)
 {
  var baseDir = AppDomain.CurrentDomain.BaseDirectory.Replace("\\bin", string.Empty) + "\\Migrations";

  context.Database.ExecuteSqlCommand(File.ReadAllText(baseDir + "\\DataClear.sql"));
  context.Database.ExecuteSqlCommand(File.ReadAllText(baseDir + "\\Table1Insertssql"));
  context.Database.ExecuteSqlCommand(File.ReadAllText(baseDir + "\\Table2Inserts.sql"));
 }
}

The above code will execute DataClear.sql, Table1Inserts.sql and Table2Inserts.sql, which are all in the root of my migrations folder.

Don’t forget that you can generate your insert statements using management studio, or by using the Static Data Generator tool.