Search code examples
asp.net-mvc-3entity-frameworkentity-framework-4objectcontext

Not tracking a single property of an entity with EF4


My MVC action method receives an entity object (Page) that the default model binder creates from form collection data. Some of the fields are wrong or null because they were not sent in the request to the server, for example I do not send "CreateDate" and the default model binder sets this property to some default value which I don't need.

Once the object is attached it of course tries to persist all the values (including invalid/not needed ones to the database). I could of course assign manually on a per property basis but was wondering if maybe I can somehow flag a property so it is not persisted when EntityState is set to modified and SaveChanges() is called..

public ActionResult SomeMethod(Page page)
{
page.ModifyDate = DateTime.Now;

       _db.NewsPages.Attach(page);
                _db.ObjectStateManager.ChangeObjectState(page, System.Data.EntityState.Modified);
                _db.SaveChanges();
                _db.Dispose();

}

Solution

  • The correct way to handle this is using different class for view model, attach empty entity to the context and assign real values per property (or let AutoMapper to handle this scenario) as @Darin suggested in the comment.

    If you want to go your way you must not change state of the POCO entity but you must change state of every changed property:

    public ActionResult SomeMethod(Page page)
    {
        page.ModifyDate = DateTime.Now;
    
        _db.NewsPages.Attach(page);
        ObjectStateEntry entry = _db.ObjectStateManager.GetObjectStateEntry(page);
        entry.SetModifiedProperty("ChangedPropertyName");
        // Do the same for all other changed properties
        _db.SaveChanges();
        _db.Dispose();
    }