问题
have recently started using Code First Migrations and was wanting to seed data in each Up method.
is this possible?
Ie.
- Create database table
- Fill with data
for Drop:
- Delete data from joining table
- delete table
回答1:
Yes it is possible but you must do it through executing SQL commands. Use Sql
method in both Up
and Down
methods of your migration to execute INSERT
and DELETE
SQL commands.
回答2:
public partial class DBInitializer : IDatabaseInitializer<DBContext>
{
public void InitializeDatabase(DBContext context)
{
var cfg = new Migrations.Configuration();
var migrator = new DbMigrator(cfg);
List<string> pendingMigrations = new List<string>(migrator.GetPendingMigrations());
foreach (string migration in pendingMigrations)
{
Console.WriteLine("Updating Migration:" + migration);
migrator.Update(migration);
Console.WriteLine("Updated Migration:" + migration);
if (migration.Contains("AddMyProperty"))
{
// seed data codes
context.SaveChanges();
}
}
}
}
来源:https://stackoverflow.com/questions/11611322/ef-4-3-code-first-migrations-seed-per-migration