2017-04-20 64 views
1

我从数据库中抽出一堆时间表条目并使用它们来创建发票。一旦我保存了发票并有一个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); 
} 

回答

1

如果TimeEntry有关联Invoice(检查导航属性),你也许可以做这样的事情:

var timeEntries = context.TimeEntries.Where(t => timeEntryIds.Contains(te.Id)).ToArray(); 

foreach(var timeEntry in timeEntries) 
    invoice.TimeEntries.Add(timeEntry); 

context.Invoices.Add(invoice); 

//save the entire context and takes care of the ids 
context.SaveChanges(); 
+0

而不是这样做,我添加了TimeEntries我保存之前的发票。 invoice.TimeEntries = context.TimeEntries.Where(te => timeEntryIds.Contains(te.Id))。ToArray() –

1

您简化语法后的表现?

我会建议使用直接的SQL查询,

string query = "Update TimeEntries Set InvoiceId = <invoiceId> Where Id in (comma separated ids)";  
context.Database.ExecuteSqlCommandAsync(query); 

对于逗号分隔的ID,你可以做string.Join(',', timeEntryIds)

这取决于你的实际需要。如果你想使用Linq,那么你需要迭代每个对象。

2

免责声明:我的项目Entity Framework Plus

我们的图书馆有一个批量更新功能,我相信的主人是你在找什么

此功能支持EF核心

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

维基百科:EF Batch Update