0
votes

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?

@IvanStoev thanks a lot for quick answer. Just one more question - if I create a custom migration to be used in code, How can I keep it hidden from the migration runner CLI or from EnsureMigrated() method? - harishr
EF Core IMigrator services 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
@IvanStoev it all started from here, some way to add column dynamically. - harishr
and yes, please add your comment as answer. - harishr