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

标签 c# entity-framework linq bulkupdate entity-framework-extended

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

相关文章:

linq - NHibernate Linq GroupBy 多个属性不起作用

c# - SQLite 正在为内存数据库创建磁盘文件

c# - 为什么在使用 MvxWpfSetup<Core.App> 作为 RegisterSetupType 时收到错误 CS0310

c# - Response.Redirect 的正确使用方法

c# - 从命令行生成 EF 存储过程方法

.net - 将 Entity Framework 与历史数据一起使用

c# - 对目录中的文件名进行排序,给出错误排序的结果

c# - 将 IList<T1> 转换为 ILIst<T2>

c# - 比较 C# DateTime 和 MySql 日期

asp.net-mvc - 我们应该使用 Entity Framework Code First 方法在 MVC 应用程序中使用 Data Repository 模式吗?