我一直在自定义代码中使用流利的迁移器,可以在其中注入IMigrationRunner并运行任何迁移。
例如
public class CreateTableMigration : Migration
{
public static string SchemaName { get; } = "mst";
private readonly MasterTable _table;
public CreateTableMigration(MasterTable table)
{
_table = table;
}
private string PrimaryKeyName => $"PK_{SchemaName}_{_table.Name}_Id";
public override void Up()
{
Create.Table(_table.Name).InSchema(SchemaName)
.WithColumn("Id").AsInt64().Identity().PrimaryKey(PrimaryKeyName);
}
public override void Down()
{
Delete.Table(_table.Name).InSchema(SchemaName);
}
}
然后可以从代码中应用此虚拟迁移:
public class AppDbMigration : IAppDbMigrator
{
private readonly AppDbContext _dbContext;
private readonly IMigrationRunner _migrationRunner;
public AppDbMigration(AppDbContext dbContext, IMigrationRunner migrationRunner)
{
_dbContext = dbContext;
_migrationRunner = migrationRunner;
}
private void CreateTable(MasterTable table)
{
if (!table.IsMigrationPending()) { return; }
if (table.MasterColumns.All(x => x.Name != "Name"))
{
throw new MyHandledException("Name column is mandatory");
}
_migrationRunner.Up(new CreateTableMigration(table));
SaveTableAsMigrated(table.Id);
}
}
Ef-Core迁移中是否存在类似于IMigrationRunner的内容?或者如何使用EF core从代码运行一些自定义迁移?