Bulk Update in Entity Framework Core

.net c# entity-framework entity-framework-core

Question

I pull a bunch of timesheet entries out of the database and use them to create an invoice. Once I save the invoice and have an Id I want to update the timesheet entries with the invoice Id. Is there a way to bulk update the entities without loading them one at a time?

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);
}
2
4
11/11/2019 7:40:18 AM

Accepted Answer

If TimeEntry has an association to Invoice (check the navigation properties), you can probably do something like this:

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();
4
4/20/2017 11:49:34 PM

Expert Answer

Disclaimer: I'm the owner of the project Entity Framework Plus

Our library has a Batch Update feature which I believe is what you are looking for

This feature supports EF Core

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

Wiki: EF Batch Update

EDIT: Answer comment

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 support contains: https://dotnetfiddle.net/DAdIO2

13
1/14/2020 1:21:23 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow