EF 核心仅更新大型表的特定字段的最佳方法

问题描述 投票:0回答:4

我试图找到使用 EF core 仅更新特定字段的最佳方法。 问题是有很多字段,将每个字段标记为已修改并更改其值会使代码变得非常长且复杂。

有没有一种方法至少可以通过一个命令设置新值并标记为已修改?

这就是我的代码现在的样子:

 context.Entry(obj).Property("name").IsModified = true;
 obj.name="Dan";

每个字段都会如此(大约 30 个字段,但表格要大得多)。

我也尝试过这个:

context.Entry(obj).Property("name").CurrentValue="Dan";
context.SaveChangesAsync();

但它不会更新任何记录。

如有任何帮助,我们将不胜感激!

.net entity-framework entity-framework-core linq-to-sql
4个回答
2
投票

从数据库获取对象后,只需更新属性值并调用

SaveChanges
。 EF 将生成一个查询,仅更新具有新值的属性。

var myObj = await this.context.FindAsync(id);
myObj.Property1 = 42;
myObj.Property2 = "new value";
...

await this.context.SaveChangesAsync();

附注确保启用更改跟踪。


0
投票

我通常使用这个算法

 var existingObj = await Context.Set<obj>().FindAsync(id);//or use FirstOrDefault()

 if (existingObj== null) return ...error;

existingObj.Name="name"
Context.Entry(existingObj).Property(i=>i.Name).IsModified = true;
Context.SaveChanges();

0
投票

从 EF Core 7 开始,您可以使用 ExecuteUpdate 功能:

context.Users
    .Where(u => u.Id == userId)
    .ExecuteUpdate(s => s.SetProperty(u => u.Name, "Dan"));

用于更新多个字段的流畅语法:

context.Users
    .Where(u => u.Id == userId)
    .ExecuteUpdate(s => s
        .SetProperty(u => u.Name, "Dan")
        .SetProperty(u => u.LastName, "Bar")
    );

-1
投票

我要补充的是:

 context.ChangeTracker.AutoDetectChangesEnabled = true;

然后我就可以像这样更新它:

context.Entry(obj).Property("name").CurrentValue="Dan";
context.Entry(obj).Property("lastName").CurrentValue="Bar";
.
.
.
await context.ApplyChangesAsync();
© www.soinside.com 2019 - 2024. All rights reserved.