EF - Update multiple rows in database without using foreach loop

c# entity-framework linq

Question

My test code:

using (var db = new MyDbContext())
{
  string fromUser = ""; //sender
  string toUser = ""; //receiver

  var messages = db.Message.Where(x => x.FromUser == fromUser && x.ToUser == toUser)
                 .ToList();

  foreach (var message in messages)
  {
    message.IsRead = true;
    db.SaveChanges();
  }
}

My question: is there another way to update database without using foreach loop in that case?

p/s: I'd been reference these questions but all of them didn't solve my problem:

1
11
5/23/2017 11:54:50 AM

Accepted Answer

You don't need to SaveChanges() on each iteration. That will hit the database multiple times. Try:

using (var db = new MyDbContext())
{
  string fromUser = ""; //sender
  string toUser = ""; //receiver
  var messages = db.Message.Where(x => x.FromUser == fromUser && x.ToUser == toUser)
                 .ToList();
  messages.ForEach(m => m.IsRead = true);
  db.SaveChanges();
}
24
12/5/2015 4:43:01 PM

Popular Answer

Just to update Steve's answer, in newer EF (current EF Core 3.1.3) you can do it all as one statement.

await db.Message.Where(m => m.FromUser == fromUser && m.ToUser == toUser).ForEachAsync(m => m.IsRead = true);
await db.SaveChangesAsync().ConfigureAwait(false);


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