Stephen Stephen - 17 days ago 8
C# Question

Prevent property from being updated by Entity Framework

What's the best way to prevent my CreatedOn property from being overwritten, please see below:

public class MyObject
{
...
public DateTime? CreatedOn { get; set; }
...
}


I know that I can pass it to the view and use a hidden object, but I don't want to rely on that.

My update method looks like this:

var originalObject = db.Object.Find(model.objectId);

if (originalObject != null)
{
...
db.Entry(originalObject).CurrentValues.SetValues(model);
db.SaveChanges();
}


I was trying to prevent doing a read and setting each property individually. Also, I don't have the CreatedOn method listed in the Bind list, so the value in the database is being overwritten with NULL or throwing an error that it can't be NULL, depending on the way that I have the property setup in the model.

Answer

You can use property IsModified to define if specific entity property was modified:

db.Entry(originalObject).CurrentValues.SetValues(model);
db.Entry(originalObject).Property(o => o.CreatedOn).IsModified = false;
db.SaveChanges();

When set to false, column will not be updated in the database.

As you can see, as you want to exclude more properties, you need to write more code. It is very easy to forget exclusion when some new properties are added as well. Therefore, I recommend using view models where appropriate. When using view model, instead of entity you are using custom object with only properties that make sense for your specific view. It is a huge topic to cover in SO answer, but you can read a good introduction to the topic.