我试图使用实体框架批量更新记录。我尝试过实体Framework.Extensions Update方法。
Update方法能够对一组具有相同更新值的记录进行大容量更新。
示例:
Id - Quantity
Record 1 - A - 10
Record 2 - B - 20
Record 3 - C - 30我们可以通过简单的调用来批量更新上述所有记录。
Records.Update(new => Record { Quantity = 100 });如何使用Entityframework.Extensions或任何其他方法以不同的数量批量更新每条记录,从而更快地完成批量更新?
发布于 2017-05-29 17:24:12
如果不想使用SQL语句,可以使用附加方法来更新实体,而不必先加载它:
using (myDbEntities db = new myDbEntities())
{
try
{
//disable detection of changes to improve performance
db.Configuration.AutoDetectChangesEnabled = false;
//for all the entities to update...
MyObjectEntity entityToUpdate = new MyObjectEntity() {Id=123, Quantity=100};
db.MyObjectEntity.Attach(entityToUpdate);
//then perform the update
db.SaveChanges();
}
finally
{
//re-enable detection of changes
db.Configuration.AutoDetectChangesEnabled = true;
}
}发布于 2017-05-26 06:21:45
using (yourDbEntities db = new yourDbEntities())
{
db.Database.ExecuteSqlCommand("UPDATE YourTABLE SET Quantity = {0} WHERE Id = {1}", quantity, id);
}yourDbContext.ExecuteStoreCommand("UPDATE YourTABLE SET Quantity = {0} WHERE Id = {1}", quantity, id);发布于 2022-02-05 10:52:06
将有内置的BulkUpdate()和BulkDelete方法在EFCore中,并将在EFCore 7.0中交付。
context.Customers.Where(...).BulkDelete();
context.Customers.Where(...).BulkUpdate(c => new Customer { Age = c.Age + 1 });
context.Customers.Where(...).BulkUpdate(c => new { Age = c.Age + 1 });https://stackoverflow.com/questions/44194877
复制相似问题