The following save all in once, How do I make a batch of 50 and save a batch instead of saving all in once.
dbUserList will have around 50k objects.
var dbUserList = db.Users.Where(x => users.Select(y => y.Id).Contains(x.Id));
foreach (var user in users)
{
var dbUser = dbUserList.First(x => x.Id == user.Id);
dbUser.name = user.name;
dbUser.cat = user.cat;
}
db.SaveChanges();
foreach (var user in users)
{
db.Users.Attach(user);
db.Entry(user).State = System.Data.Entity.EntityState.Unchanged;
db.Entry(user).Property(c=> c.name).IsModified=true;
db.Entry(user).Property(c=> c.cat).IsModified=true;
}
db.SaveChanges();
i think this is what you wanted. update them all without query them all.
You need to use skip/take in LINQ to get around this. The code below should work. Although I'm not always a fan of doing a while(true) with a break statement, it's the easiest way to implement this.
int takeCount = 50;
int skipAmount = 0;
while (true)
{
var dbUserList = db.Users.Where(x => users.Select(y => y.Id).Contains(x.Id)).OrderBy(x => x.Id).Skip(skipAmount).Take(takeAmount);
if (!dbUserList.Any)
{
break;
}
foreach (var user in users)
{
var dbUser = dbUserList.First(x => x.Id == user.Id);
dbUser.name = user.name;
dbUser.cat = user.cat;
}
db.SaveChanges();
}
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.