I have an ASP.NET MVC view for editing a model object. The edit page includes most of the properties of my object but not all of them — specifically it does not include CreatedOn and CreatedBy fields since those are set upon creation (in my service layer) and shouldn’t change in the future.
Unless I include these properties as hidden fields they will not be picked up during Binding and are unavailable when I save the modified object in my EF 4 DB Context. In actuality, upon save the original values would be overwritten by nulls (or some type-specific default).
I don’t want to drop these in as hidden fields because it is a waste of bytes and I don’t want those values exposed to potential manipulation.
Is there a “first class” way to handle this situation? Is it possible to specify a EF Model property is to be ignored unless explicitly set?
Use either:
(Edit: The query only loads the
CreatedOncolumn from the database and is therefore cheaper and faster than loading the full entity. Because you only need theCreatedOnproperty usingFindwould be unnecessary overhead: You load all properties but need only one of them. In addition loading the full entity withFindand then detach it afterwards could be shortcut by usingAsNoTracking:db.Recordings.AsNoTracking().SingleOrDefault(r => r.Id == recording.Id);This loads the entity without attaching it, so you don’t need to detach the entity. UsingAsNoTrackingmakes loading the entity faster as well.)Edit 2
If you want to load more than one property from the database you can project into an anonymous type:
(End of Edit 2)
Or:
(Edit: Using
CurrentValues.SetValuesflags only properties as Modified which indeed have been changed compared to the original state in the database. When you callSaveChangesEF will sent only the properties marked as modified in an UPDATE statement to the database. Whereas setting the state inModifiedflags all properties as modified, no matter if they really changed or not. The UPDATE statement will be more expensive because it contains an update for all columns.)