我有一个代码优先的方案,启用了迁移,AutomaticMigrationsEnabled
被禁用,并且数据库初始化程序设置为MigrateDatabaseToLatestVersion
。我想"赶上"用于记录目的的迁移事件。
我尝试在Seed()
中进行此操作,但每次运行都会调用它,无论底层数据库是否需要迁移以匹配模型。
有没有正确的方法呢?
答案 0 :(得分:2)
解决方案1)
检查您是否需要迁移:
var migrator = new DbMigrator(new DbMigrationsConfiguration());
// If any migration is required then Count will be greater than 0
// 0 means no migration required
if (migrator.GetPendingMigrations().Count() > 0)
{
// Fire your event here!
}
灵魂2) 使用日志记录装饰器记录进度,在此用例中您不需要事件。
public class MyLogger : System.Data.Entity.Migrations.Infrastructure.MigrationsLogger
{
public override void Info(string message)
{
// Short status messages come here
}
public override void Verbose(string message)
{
// The SQL text and other info comes here
}
public override void Warning(string message)
{
// Warnings and other bad messages come here
}
}
要迁移到最新版本,您必须像这样调用它:
DbMigrator migrator = new DbMigrator(new MyConfiguration());
MigratorLoggingDecorator logger = new MigratorLoggingDecorator(migrator, new MyLogger());
// This line will call the migration + logging
logger.Update();
额外信息:
您可以像这样创建自定义MigratorLoggingDecorator decroator:
MyMigratorLoggingDecorator: MigratorLoggingDecorator {
internal override Upgrade(IEnumerable<string> pendingMigrations, string targetMigrationId, string lastMigrationId)
{
// Fire your event here!
base.Upgrade(..)
}
..}