gpt4 book ai didi

entity-framework - EF 核心 : Add custom LINQ in Up method of Migration class

转载 作者:行者123 更新时间:2023-12-05 05:17:19 24 4
gpt4 key购买 nike

我想在迁移的 Up 方法中执行一些 LINQ。问题是我不知道如何获取 DbContext 实例?

这是由 migrations add 生成的代码:

public partial class MyTableAddFieldTitle : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Title",
table: "MyTable",
nullable: true);
}

protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Title",
table: "MyTable");
}
}

我想在 Up 方法中添加类似的东西:

protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Title",
table: "MyTable",
nullable: true);

var context = ?????;

//Actual code is much more complicated, but the principle is the same.
foreach (var item in context.Set<DbMyTable>())
item.Title = item.SomeStringColumn;
context.SaveChanges();
}

问题是如何获取上下文实例?我在构造函数中尝试使用 DI:

protected MyTableAddFieldTitle(MyContext context)
{
}

但我得到错误:

MissingMethodException: No parameterless constructor defined for this object. System.RuntimeTypeHandle.CreateInstance(RuntimeType type, bool publicOnly, ref bool canBeCached, ref RuntimeMethodHandleInternal ctor)

最佳答案

我找到了解决方案。

Startup 类中我定义了静态变量:

public static Func<MyContext> ContextFactory;

Startup 类的构造函数中,我分配了变量:

public Startup(IHostingEnvironment env, IConfiguration config)
{
MyContext GetContext(IConfiguration configuration, IHostingEnvironment environment)
{
var builder = new DbContextOptionsBuilder<MyContext>();
builder.UseSqlServer(configuration["ConnectionStrings:Web"], b => b.MigrationsAssembly("Web.Hosting"));
if (environment.IsDevelopment())
builder.EnableSensitiveDataLogging();
return new MyContext(builder.Options);
}

ContextFactory = () => GetContext(config, env);
}

然后在迁移中,我只需调用 ContextFactory:

var context = Startup.ContextFactory();
context.Set<DbMyTable>().Where(....

为避免错误字段不存在,我创建了 2 个迁移文件(dotnet ef migrations add)。
首先添加字段:

protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Title",
table: "MyTable",
nullable: true);
}

第二个(空)执行查询:

protected override void Up(MigrationBuilder migrationBuilder)
{
var context = Startup.ContextFactory();
context.Set<DbMyTable>().Where(....
}

关于entity-framework - EF 核心 : Add custom LINQ in Up method of Migration class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49400742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com