This post applies to EF 4.1 and above.
In a recent post I demonstrated how to delete a record from your data source without first selecting it. I’ve found this idea to be most relevant when using MVC. I don’t want a tonne of hidden fields in my form in order to get a complete entity that I can post to my controller, when all I need to delete a record is it’s primary key or id.
If my site has been properly developed, I may have a view model which contains only the data which my view needs. My view contains editable fields only. I don’t have a fully populated entity.
I could use the posted data to retrieve an entity from the data source, update it, and then save it. In the case of a SQL data source, this will result in two queries. One to select the record, and another to update it.
The principle is the same for updating records without selecting them as it is in my earlier post about deleting records.
There’s another big point to note when using EF with MVC. You can still post a partially complete model to your controller action. MVC will map the posted fields to those of your model. Any that are missing will be filled with default values, i.e. it will contain values for fields you haven’t edited. Integral properties will be initialised to zero, and reference types will be null. Now, if you attach this model to your data context, and call
SaveChanges(), these values will overwrite your data, or if the model doesn’t have it’s
Key property populated, no data will be updated at all. An even worse scenario is possible, where a malicious user could provide their own form fields matching your table column names and update fields you didn’t intend to be editable!
Despite this however, I still pass the model to the controller action in this way. I just don’t use it directly as an entity for updating. My controller actions have no idea I’m using EF anyway. They simply grab the fields they need from the posted model, and send them to a properly injected data management repository. The repository is where the above code is homed. You can of course use the above code directly within your controller actions if you’re not using the repository pattern, but you’re then left wide open to attacks from gonad-eating vulture demons. Check back soon for details of a lesser known chapter of Darwin’s ‘The Origin of Species’, about vulture demons and their part in natural selection.