entity-frameworkentity-framework-4.1

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?


Solution

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