首页 > 解决方案 > 动态表创建 - ef 核心迁移

问题描述

我一直在自定义代码中使用流利的迁移器,我可以在其中注入 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 Migrations 中是否存在类似于 IMigrationRunner 的内容?或者如何使用 EF 核心从 Code 运行一些自定义迁移?

标签: c#entity-framework-coreentity-framework-migrationsfluent-migrator

解决方案


推荐阅读