Many times when developing databases, you would need some kind of post-deployment script, which is basically a script that will run after every time you deploy your database schema. Ideally post-deployment script should run automatically each time you deploy database.
In this post I explain how to create post-deployment script when working with EF Migrations.
Step 1:
First you need to create an .sql file which will hold your SQL script. I prefer to place it in the Migrations folder and call it Seed.sql:
Please note that Seed.sql is a pure SQL script and as such cannot contain SQLCMD commands, such as go
, otherwise you will get an error when trying to Update-Database
.
Step 2:
Next you should make sure to set the Build Action to “Embedded Resource”:
Step 3:
Now the last part is go into your Configuration.cs and call the script from there, as so:
protected override void Seed(ExampleDbContext context)
{
base.Seed(context);
using (var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Example.Migrations.Seed.sql"))
{
using (var ms = new StreamReader(stream))
{
var sql = ms.ReadToEnd();
context.Database.ExecuteSqlCommand(sql);
}
}
}
That’s it! Simple and effective.