gpt4 book ai didi

c# - 如何批量更新 Entity Framework 中的记录?

转载 作者:可可西里 更新时间:2023-11-01 07:50:48 31 4
gpt4 key购买 nike

我正在尝试使用 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com