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

30th Oct 2012

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.