I have been using fluent migrator in custom code, where I can inject IMigrationRunner and run any migration.
E.g.
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);
}
}
And then can apply this dummy migration from code:
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);
}
}
Does something similar to IMigrationRunner exist in Ef-Core Migrations? Or how can I run some custom migrations from Code using EF core?
IMigratorservices allow running at runtime the same migrations as at "design" time (using the tools). Migrations are incremental, and there is no such concept as "runtime-only" or "design time-only" migration. Note that you can only run migrations at runtime - they have to be created at design time using "add-migration" commands. Shortly, not sure why you need that, but it's not possible out-of-the box. - Ivan Stoev