如何在Entity Framework中批量更新记录? [英] How to Bulk Update records in Entity Framework?
问题描述
我正在尝试使用Entity Framework批量更新记录.我尝试了Entity Framework.Extensions Update
方法.
I am trying to bulk update records using Entity Framework. I have tried Entity Framework.Extensions Update
method.
Update
方法能够批量更新具有相同更新值集的一组记录.
The Update
method is able to bulk update for a set of records with same set of update values.
示例:
Id - Quantity
Record 1 - A - 10
Record 2 - B - 20
Record 3 - C - 30
我们可以通过简单的调用
We can bulk update all the above records by simple calling
Records.Update(new => Record { Quantity = 100 });
如何使用Entityframework.Extensions
或任何其他方式批量更新具有不同数量的每条记录,从而更快地完成批量更新?
How can I bulk update each record with different quantity using Entityframework.Extensions
or in any other approach, which completes the bulk update faster?
推荐答案
如果您不想使用SQL语句,则可以使用Attach方法来更新实体,而不必先加载它:>
If you don't want to use an SQL statement, you can use the Attach method in order to update an entity without having to load it first :
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;
}
}
这篇关于如何在Entity Framework中批量更新记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!