12

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
  • Move the SaveChanges() outside of the for loop Commented Dec 5, 2015 at 16:43

2 Answers 2

27

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();
}
Sign up to request clarification or add additional context in comments.

5 Comments

Creating a list and lambda just to call a method which internally is a loop. Crazy people.
Well, the bigger point is certainly the single database call. Some would argue the lambda looks cleaner (it's a resharper recommended refactoring). Crazy is a little harsh IMO.
@SteveGreene The comment was not for your or your solution, I understand that was the OP request. Indeed a single database call is the point, but not from the post title, which moves the focus on the unimportant thing. List<T>.ForEach is a mistake - blogs.msdn.com/b/ericlippert/archive/2009/05/18/…
Simple and Direct approached and saved alot of process time. Thanks
8

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.