-1
var results = context.Customer.Where(c => c.CustomerId == customerId).AsQueryable();

foreach(Customer cust in results)
{
    cust.isDeleted = true;
}

context.UpdateRange(results);
context.SaveChanges();

** Using the loop seems inefficient. Can the fetch and update be done in a single statement?

HABosch
  • 49
  • 3
  • 1
    Does this answer your question? [Bulk Update in Entity Framework Core](https://stackoverflow.com/questions/43531602/bulk-update-in-entity-framework-core) – Peter B Aug 25 '21 at 14:09

1 Answers1

1

If you want better performance, execute SQL instead:

context.Database.ExecuteSqlCommandAsync($"UPDATE Customer SET isDeleted = 1 WHERE CustomerId = {customerId}");

EF Core will protect from injection and generate a SQL parameter for you.

EDIT: As Peter has pointed out in the comments, keep in mind that this will cause any entities already loaded to be out of sync with the database.

JuanR
  • 7,405
  • 1
  • 19
  • 30
  • 1
    A note should probably be added that if any of these records had already been loaded into the DbContext, then after this they will have an outdated value in their `isDeleted` properties. – Peter B Aug 25 '21 at 14:27