I'm running into problems when I try to save entities that have a parent/child relationship in EF4. Sometimes, the child will be inserted before the parent - which obviously will cause problems from a referential constraint point of view. The two tables are structured like this:
OrderHeader
- OrderID (PK)
OrderDetails
- OrderID (PK)
- DetailID (PK)
(there are more columns, but they don't matter).
Note: We don't expose a true foreign key on OrderDetails.OrderID but instead we use triggers to enforce that the OrderID of the Details table exists in the Header table. Exposing FKs might be a quick solution but in the our application, those kinds of changes to the database won't be allowed - we have to deal with legacy code, etc.
Looking at the XML in the .edmx file that the designer generates, I've noticed that it makes an AssociationSet and Association in the Conceptual Model (CSDL section) - and the Association is setup with a ReferentialConstraint. However, it doesn't make an AssociateSet or Assocation in the SSDL section. It seems like those only get added when the FK is exposed in the database. For other databases I've tested on (like AdventureWorks or Northwind) that do have true FKs in the database, when I generate the model from the database, I see that the EDMX includes Association and AssociationSet sections in the SSDL.
It appears that EF ignores the association that we have in the model (CSDL) and instead just does inserts alphabetically by table name - so we are out of luck in this case since OrderDetail sorts before OrderHeader (and we certainly don't have the power to rename tables in our case). If I manually add a corresponding AssociationSet and Association in the SSDL section, the save occurs in the correct order (first insert Header, then insert Detail). However, anytime we do an 'Update Model from Database' those manual changes go away so it's not a very practical solution. I've thought about trying to do that fix-up dynamically at runtime but it feels like that is a lot of effort to work around something that should 'just work'.
I'm hoping there is a way that EF can respect the Referential Constraint and/or Association that is defined in the CSDL when it orders Inserts.