最近开始使用 Code First 迁移,并希望在每个Up方法中播种数据。
这可能吗?
IE。
- 创建数据库表
- 填写数据
对于下降:
- 从连接表中删除数据
- 删除表
最近开始使用 Code First 迁移,并希望在每个Up方法中播种数据。
这可能吗?
IE。
对于下降:
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.
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();
}
}
}
}