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 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 🙂

Published by Nirbhay

Technology Geek,Blogger,Reviewer

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.