Wednesday, June 20, 2012

Entity Framework 4 - Batch Updates

This article explains the batch update of data into data base using the Entityframework4.

Problem Statement:  We have a List of customer that needs to be updated in the data base.
I will directly jump on the code.

Here is the function which does the Batch update in a single database hit.

 public JsonResult Update(List<Customer> models)  
     {  
       using (var context = new NorthwindEntities())  
       {  
         //Attach each entity to a context entity  
         models.ForEach(a => context.Customers.Attach(a));  
         //Change all the object state to Modified  
          models.ForEach(s => context.ObjectStateManager.ChangeObjectState(s,   
                        EntityState.Modified));               
         //Save changes to the database    
         context.SaveChanges();  
       }  
        //Return the result  
       return Json(Details());  
     }  

 Note: Instead  EntityState.Modified you can use Added/Deleted/Detached

Happy Coding :)

No comments:

Post a Comment