How to Bulk Update records in Entity Framework?

前端 未结 7 2190
遥遥无期
遥遥无期 2020-12-01 08:00

I am trying to bulk update records using Entity Framework. I have tried Entity Framework.Extensions Update method.

The Update method is abl

7条回答
  •  庸人自扰
    2020-12-01 08:36

    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;
        }
    }
    

提交回复
热议问题