作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想在迁移的 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/
我是一名优秀的程序员,十分优秀!