Entity Framework - Change Track & Update Entities based on Views
|
I get asked a lot about using views in an EDM and updating the entities that map to those views. You can definitely do this. Here's an overview of how this works along with some rules you should be prepared for when implementing this scenario in your model. EF will change track entities that are mapped to views, however it won't automatically create the DML commands when you call SaveChanges. But It is still possible to push the changes (& inserts & deletes) by mapping the entity to stored procedures. In EF, if you do function mapping, where you indicate in the model that a set of Insert, Update and Delete stored procs should be used for a particular entity. Then when you call SaveChanges, EF will will used these sprocs instead of dynamically building the commands. If you happen to have my book, Programming Entity Framework, there is a whole chapter devoted to function mapping to stored procedures. If you don't have the book, check out this MSDN Documentation article on the topic [How to: Map Modification Functions to Stored Procedures] There are a few rules to be prepared for before embarking on function mapping. 1) You must have an insert, update and delete function for the entity. You won't be able to map one of those funcitons and then rely on the dynamically built commands for the others. I believe this rule will be relaxed in EF4. 2) Insert & update parameters can only come from entity properties. You can 't just push a scalar value into there. 3) If the entity has any entity references (e.g. if your entity is an order and has a refererence to customer) all of the stored procs must take that FK as a parameter. Even the delete sproc. This makes sense for inserts and updates, but is strange for deletes. The EF needs it but it is not the way most delete stored procs are written. You'll have to make that accommodation. 4) If the entity is part of an inheritance hierarchy, all of they will need to use function mappings, all of the entities in the hierarchy must also use function mapping. 5) This last one is from an upcoming "EF gotchas" article that I have written for Code magazine:
|

