gpt4 book ai didi

c# - Entity Framework Core 中的批量更新

转载 作者:行者123 更新时间:2023-11-30 13:14:35 25 4
gpt4 key购买 nike

我从数据库中提取了一堆时间表条目并使用它们来创建发票。保存发票并获得 ID 后,我想使用发票 ID 更新时间表条目。有没有一种方法可以批量更新实体而无需一次加载一个实体?

void SaveInvoice(Invoice invoice, int[] timeEntryIds) {
context.Invoices.Add(invoice);
context.SaveChanges();

// Is there anything like?
context.TimeEntries
.Where(te => timeEntryIds.Contains(te.Id))
.Update(te => te.InvoiceId = invoice.Id);
}

最佳答案

免责声明:我是项目的所有者Entity Framework Plus

我们的图书馆有批量更新功能,我相信这就是您正在寻找的功能

此功能支持 EF Core

// Is there anything like? YES!!!
context.TimeEntries
.Where(te => timeEntryIds.Contains(te.Id))
.Update(te => new TimeEntry() { InvoiceId = invoice.Id });

维基:EF Batch Update

编辑:回复评论

does it supports contains as in your example? I think this is coming from EF Core which is not supported feature in 3.1 version even

EF Core 3.x 支持包含:https://dotnetfiddle.net/DAdIO2

编辑:回复评论

this is great but this requires to have zero parameter public constructors for classes. which is not a great. Any way to get around this issue?

从 EF Core 3.x 开始支持匿名类型

context.TimeEntries
.Where(te => timeEntryIds.Contains(te.Id))
.Update(te => new { InvoiceId = invoice.Id });

在线示例:https://dotnetfiddle.net/MAnPvw

关于c# - Entity Framework Core 中的批量更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43531602/

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