2
我有啓用遷移的代碼優先方案,AutomaticMigrationsEnabled
已禁用,並且DB初始值設置爲MigrateDatabaseToLatestVersion
。爲了記錄目的,我想「捕捉」遷移事件。EF6代碼優先遷移:遷移事件
我試圖在Seed()
中這樣做,但無論基礎數據庫是否需要遷移以匹配模型,它都被稱爲每次運行。
有沒有適當的方法來做到這一點?
我有啓用遷移的代碼優先方案,AutomaticMigrationsEnabled
已禁用,並且DB初始值設置爲MigrateDatabaseToLatestVersion
。爲了記錄目的,我想「捕捉」遷移事件。EF6代碼優先遷移:遷移事件
我試圖在Seed()
中這樣做,但無論基礎數據庫是否需要遷移以匹配模型,它都被稱爲每次運行。
有沒有適當的方法來做到這一點?
解決方法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!
}
Soultion 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(..)
}
..}
這不是你正在尋找的東西,但有一個'[dbo]。[__ MigrationHistory]'表,其中包含我有關已應用於數據庫的所有遷移的信息。 –
是的我知道,但它不包含(例如)有關遷移時間戳的信息。我需要在EF啓動時記錄遷移 –