I currently am using the Microsoft Entity Framework to handle my db. I need to be able to reset one column of a table in my db somewhat quickly, and the way I am doing it right now takes quite a while and blocks up the application during the loop. This is the current code:
using (var db = new DbContext())
{
var userRepo = new UserRepository(db);
User[] users = userRepo.GetAll().ToArray();
foreach (User user in users)
{
if (user.Money != 0)
{
user.Money = 0;
db.Set<User>().Update(user);
await db.SaveChangesAsync();
}
}
}
I have checked by console logging during the loop to see the speed of each change, and it is very slow considering I have hundreds of users. Is there a way to just do a normal query to set all data in one column to something with the Entity Framework?
As @GertArnold mentioned in his comment, there is a 3rd party library called EntityFramework.Extended that lets you do a batch to update a set of specific rows. In your case it would be:
db.Set<User>().Update(u=>new User{Money=0});
await db.SaveChangesAsync();
Just install this nuget package and execute the code I show above.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.