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

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

Leave a Comment

tech