views:

91

answers:

2

Is it possible to create associates b/t 2 non-key fields in the Entity Framework?

Example: Take the 2 tables in a legacy application (i.e. keys/structure cannot change)

Order - OrderId : int : PK - OrderNo : varchar

OrderDetails - DetailRecordId : int : PK - OrderNo : varchar

In the Entity Framework, I want to create an association b/t Order and OrderDetails by the OrderNo field, which is not a primary key on either table or a FK relationship in the database.

This seems to me as not only should it be easy to do, but one reasons to use something like EF. However, it seems to only want to allow me to create associations using entity keys.

+1  A: 

The problem with using non-key fields to define relationships is that the keys are not guaranteed to be properly navigatable. That could lead to a situation where you have a one to one relationship between two entities where there are more than one possible rows that fufill the relationship.

...when relating data from a database, the relationships should always be based on keys. The keys enforce the referential integrity.

Justin Niessner
The question is though will it allow it. let's say I'm 100% certain this wouldn't happen...will EF allow me to make the relationship even though it obviously isn't good practice?
Cody C
+2  A: 

The Entity Framework allows you to claim that columns are keys and that FK constraints exist where none actually exist in the database.

That is because the SSDL (StorageModel part of the EDMX) can if necessary be manipulated by you and lie about the database.

The EF will then interact with the database as if the keys and foreign keys really do exist.

This should work, but all the normal caveats about referential integrity apply.

Hope this helps

Alex

Program Manager, Microsoft

See my Entity Framework Tips

Alex James
+1 So does this mean that I have to manually edit thge .edmx file?
Cody C
Unfortunately yes.
Alex James
Thanks again. One last question. If I do edit the EDMX, how will that work when I want to use the wizard to update the model? Will my custom changes be persisted or once I start down the "Edit EDMX" route, am I forced to make all changes manually?
Cody C
Unfortunately changes in the SSDL portion of the EDMX are overwritten when you refresh the model from the database. So yes you will need to make the changes again. However if you are using the tools to modify the conceptual model using the designer, your custom SSDL bits shouldn't be touched.
Alex James