c# - 如何在迁移中传递参数?
问题描述
我希望在初始迁移中传递参数并运行迁移运行时。(通过不使用 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);
}
}
似乎上面的方法可以解决问题。但是我应该如何运行迁移运行时?
解决方案
context.Database.Migrate()
您可以使用命令手动开始迁移(从 C# 代码) 。
检查migrate 函数的代码,你会看到它使用了一个[IMigrator][2]
生成代码的代码。
在那里您可以找到如何控制迁移程序集((IInfrastructure<IServiceProvider>)context.Database).Instance.GetService<IMigrationsAssembly>()
(请仔细检查它是否返回值)
IMigrationsAssembly
具有CreateMigration
带[TypeInfo][2]
参数的功能。
我想,这将是生成从基本迁移类动态继承的类的方法,但使用重写的构造函数参数,定义表名
推荐阅读
- html - 是否可以使用 href 链接不显示?
- r - 自定义文本输入以在 R Shiny 中获取用户名和密码
- python - 如何设置 twilio 语音 api 的 url?
- sql - 使用条件访问 SQL 组
- python - 什么是horizontalHeaderItem
- c# - Hangfire 与实体框架 - DbContext 并发问题
- angular - 关闭浏览器时是否可以更新 Angular PWA 中的服务工作者?
- linux - 主机 Ping 服务启动脚本?
- javascript - JavaScript 获取三元条件运算符的条件文本(或值数组)
- c++ - 如何在使用opencv3和opencl时选择显卡?