How to Bulk Update records in Entity Framework?

自古美人都是妖i 提交于 2019-11-27 04:26:09

问题


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

The Update method is able to bulk update for a set of records with same set of update values.

Example:

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

How can I bulk update each record with different quantity using Entityframework.Extensions or in any other approach, which completes the bulk update faster?


回答1:


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



回答2:


Use ExecuteSqlCommand:

using (yourDbEntities db = new yourDbEntities())
{
    db.Database.ExecuteSqlCommand("UPDATE YourTABLE SET Quantity = {0} WHERE Id = {1}", quantity, id);
}

Or ExecuteStoreCommand:

yourDbContext.ExecuteStoreCommand("UPDATE YourTABLE SET Quantity = {0} WHERE Id = {1}", quantity, id);



回答3:


Use this way if you just want to modify few properties:

   foreach (var vSelectedDok in doks)
                    {
                        //disable detection of changes to improve performance
                        vDal.Configuration.AutoDetectChangesEnabled = false;

                        vDal.Dokumente.Attach(vSelectedDok);

                        vDal.Entry(vSelectedDok).Property(x=>x.Status).IsModified=true;
                        vDal.Entry(vSelectedDok).Property(x => x.LastDateChanged).IsModified = true;
    }
    vDal.SaveChanges();



回答4:


Bulk Update can be done in three steps with simple EF instead of separate extension methods :-

  • Load all the entities first.
  • Foreach on each entity and change its field values.
  • After Foreach save the context changes once.

This will send multiple Update queries in single batch.



来源:https://stackoverflow.com/questions/44194877/how-to-bulk-update-records-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!