首页 > 解决方案 > 如何在迁移中传递参数?

问题描述

我希望在初始迁移中传递参数并运行迁移运行时。(通过不使用 PM 命令的 c# 代码)

在下面的示例中,我正在尝试通过构造函数(参数名称 tableName)

public interface IDbContextSchema
{
    string TableName { get; set; }
}

public partial class v1 : Migration, IDbContextSchema
{
    public string TableName { get; set;}

    public v1(string tableName)
    {
        TableName = tableName;
    }

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: TableName,
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("SqlServer:Identity", "1, 1"),
                CustomerName = table.Column<string>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey($"PK_WU_{TableName}", x => x.Id);
            });
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable(
            name: TableName);
    }
}

似乎上面的方法可以解决问题。但是我应该如何运行迁移运行时?

标签: c#entity-frameworkentity-framework-core

解决方案


context.Database.Migrate()您可以使用命令手动开始迁移(从 C# 代码) 。

检查migrate 函数的代码,你会看到它使用了一个[IMigrator][2]生成代码的代码。

在那里您可以找到如何控制迁移程序集((IInfrastructure<IServiceProvider>)context.Database).Instance.GetService<IMigrationsAssembly>() (请仔细检查它是否返回值)

IMigrationsAssembly具有CreateMigration[TypeInfo][2]参数的功能。

我想,这将是生成从基本迁移类动态继承的类的方法,但使用重写的构造函数参数,定义表名


推荐阅读