我正在尝试使用 Entity Framework 批量更新记录。我试过 Entity 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
或任何其他方法批量更新不同数量的每条记录,从而更快地完成批量更新?
最佳答案
如果您不想使用 SQL 语句,可以使用 Attach 方法来更新实体,而无需先加载它:
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;
}
}
关于c# - 如何批量更新 Entity Framework 中的记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44194877/