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:

</pre>
<pre>internal sealed class Configuration : DbMigrationsConfiguration&lt;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"));
 }
 }</pre>
<pre>

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.

 

Leave a Reply

Your email address will not be published. Required fields are marked *