Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Bulk Update records in Entity Framework?

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?

like image 769
Ujjwal27 Avatar asked May 26 '17 06:05

Ujjwal27


People also ask

What is bulk insert in Entity Framework?

The EF Bulk Insert feature let you insert thousands of entities in your database efficiently. This feature is provided by the library EF Extensions (Included with EF Classic). EF Extensions is used by over 2000 customers all over the world and supports all Entity Framework versions (EF4, EF5, EF6, EF Core, EF Classic).

What is bulk update?

A bulk update definition specifies a number of conditions and a single update function. A policy must satisfy all the specified conditions in order for it to updated by the function. Bulk updates are executed through a global activity. The bulk update definition code is a parameter of this activity.


2 Answers

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;     } } 
like image 181
Grégory Bourgin Avatar answered Sep 23 '22 06:09

Grégory Bourgin


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); 
like image 26
Salah Akbari Avatar answered Sep 25 '22 06:09

Salah Akbari