Entity Framework can track changes only for context-bound objects. Objects created by the context are automatically attached to the context that creates them. Since the object you get is created by MVC, the Entity Framework does not know which values โโwere updated and which were not.
There are a few tricks you can use to tell the Entity Framework that the item has been modified. One of them is to extract the object from the context, set the changed values โโfor the object associated with the context, and then save the changes. Another is to do something like this to explicitly tell the ObjectStateManager context that some properties have been changed:
My team completed the development of a framework that automatically loads an object from the context, determines which properties differ from the new one that passed, and sets these properties to the values โโprovided by the unbound object. This approach may be of interest to you. There is a small chance that something like AutoMapper can be done for you, but I'm not sure.
Edit
Shea mentions using the UpdateModel controller method to effectively disable property value settings until you extract an entity object from your context. It sounds like a good approach, like any one for me (assuming everything is fine with the data access code in your controller), but you can use the override to create it so that you can still bind the method to the same Type object:
[HttpPost] public ViewResult EditBlogPost(BlogPost blogPost) { //This one is where I'm having issues. When model binding populates blogPost, is it auto-tracking still? For some reason SaveChanges() doesn't seem to persist the updates. if (!ModelState.IsValid) return View("ManageBlogPost"); var dbPost = db.BlogPosts.Single(bp => bp.BlogPostId = blogPost.Id); UpdateModel(dbPost, "blogPost"); db.SaveChanges(); ViewData["message"] = "Blog post edited successfully."; return View("Result"); }
Stripling warrior
source share