我有一个DbMigrationsConfiguration看起来像这样:
internal sealed class Configuration : DbMigrationsConfiguration<DatabaseProject.DB>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
AutomaticMigrationDataLossAllowed = false;
}
}
在其他地方,我的DbContext类中有:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DB, DbProject.Migrations.Configuration>(useSuppliedContext: true));
// and so on...
而且我想在应用迁移时使用MigrationsLogger记录一些信息。因此,我使用serilog设置了一个像这样的简单类:
public class EfLogger : MigrationsLogger
{
public override void Info(string message)
{
Log.Logger.Information("Machine {name} reported EF Migration Message: {message}", Environment.MachineName,
message);
}
public override void Warning(string message)
{
Log.Logger.Warning("Machine {name} reported EF Migration Warning: {message}", Environment.MachineName,
message);
}
public override void Verbose(string message)
{
Log.Logger.Verbose("Machine {name} reported EF Migration verbose message: {message}", Environment.MachineName,
message);
}
}
因此,如何更改配置以使用新的记录器?我在任何地方都找不到任何示例或文档。
我调查了它的工作原理,我认为您将无法直接使用MigrateDatabaseToLatestVersion
。不过,您应该可以覆盖它。如果您看一下实际的逻辑,它实际上很简单:
https://github.com/dotnet/ef6/blob/master/src/EntityFramework/MigrateDatabaseToLatestVersion%60.cs
public virtual void InitializeDatabase(TContext context)
{
Check.NotNull(context, "context");
var migrator = new DbMigrator(_config, _useSuppliedContext ? context : null);
migrator.Update();
}
要向其中添加日志记录,您需要在调用update之前引入一个日志记录修饰符。像这样(未经测试):
public override void InitializeDatabase(TContext context)
{
Check.NotNull(context, "context");
var migrator = new MigratorLoggingDecorator(
new DbMigrator(_config, _useSuppliedContext ? context : null),
new EfLogger());
migrator.Update();
}