How to keep existing values when editing a record using Entity Framework

I was working on a project using ASP.NET MVC and Entity Framework 5 when I encountered some problem that made me feel like banging my head on the wall.

The problem was, each time I performed an update to my record, the fields which were not bound to the update form in my Update ViewModel was always updated with a NULL or Blank value in the database. Off course, you will agree that this can be problematic should a very important piece of data get deleted this way.

Well, after spending sometime researching online on how to fix this problem I was finally able to solve this issue. In this post I want to share the solution to this problem which I found. As I am sure at some point someone would have encountered this same or someone will encounter this in the future.

Solution

Let’s assume you have a collection of properties you like to retain their existing values:

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

In EntityFramework 5 on .NET 4.5 you can do this:

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

EntityFramework 5 on .NET4.5 uses a new feature that allows a property to be set as not modified even after it has been previously set to modified.

This fix will only work in EF5 on .NET 4.5

Please comment or share if you find this tip useful

Share this: