Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update not every fields of an object using Entity Framework and EntityState.Modified

I need to update all fields except property1 and property2 for the given entity object.
Having this code:

    [HttpPost]     public ActionResult Add(object obj)     {         if (ModelState.IsValid)         {                 context.Entry(obj).State = System.Data.EntityState.Modified;                  context.SaveChanges();                         }         return View(obj);     } 

How to change it to add an exception to obj.property1 and obj.property2 for not being updated with this code?

like image 354
mhmd Avatar asked Apr 21 '12 08:04

mhmd


People also ask

How do you update an object in Entity Framework?

Update Objects in Entity Framework 4.0 The steps to update an existing entity are quite simple. First retrieve an instance of the entity from the EntitySet<T> (in our case ObjectSet<Customer>), then edit the properties of the Entity and finally call SaveChanges() on the context.

What does EntityState Modified do?

Updates are not sent to the database for entities in the Unchanged state. Added entities are inserted into the database and then become Unchanged when SaveChanges returns. Modified entities are updated in the database and then become Unchanged when SaveChanges returns.

How do I update an existing record in Entity Framework?

We can update records either in connected or disconnected scenarios. In the connected Scenario, we open the context, query for the entity, edit it, and call the SaveChanges method. In the Disconnected scenario, we already have the entity with use. Hence all we need to is to attach/add it to the context.


1 Answers

Let's assume that you have a collection of the properties to be excluded:

var excluded = new[] { "property1", "property2" }; 

With EF5 on .NET 4.5 you can do this:

var entry = context.Entry(obj); entry.State = EntityState.Modified; foreach (var name in excluded) {     entry.Property(name).IsModified = false; } 

This uses a new feature of EF5 on .NET 4.5 which allows a property to be set as not modified even after it has been previously set to modified.

When using EF 4.3.1 or EF5 on .NET 4 you can do this instead:

var entry = context.Entry(obj); foreach (var name in entry.CurrentValues.PropertyNames.Except(excluded)) {     entry.Property(name).IsModified = true; } 
like image 125
Arthur Vickers Avatar answered Sep 18 '22 18:09

Arthur Vickers