EF - Updating multiple rows in a database without using a foreach loop

My test code is:

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: is there another way to update the database without using a foreach in this case?

p / s: I mentioned these questions, but they all did not solve my problem:

+5
source share
1 answer

You do not need SaveChanges () at each iteration. This will hit the database several 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(); } 
+16
source

Source: https://habr.com/ru/post/1237465/


All Articles