Entity Framework - Add Navigation Property Manually
I generated an Entity Framework Model (4.0) from my database. I did not design the database and do not have any control over the schema, but there are a few tables that do not have foreign key constraints defined, but there is an implicit relationship defined.
For example:
I have a table called People that has the following columns: GenderID RaceID
There are tables for both Gender and Race but there is no foreign key in the People table.
When I imported the model it did not add Navigation Properties for these relationships. I tried to add it manually but From Role and To Role are disabled. I'm not sure how to add the relationship myself. How do I do this?
Solution 1:
Yup - it's not that straightforward.
Here's what you do:
1 - Right click on the designer, Add -> Association
2 - Setup the association and cardinalities (People *..1 Gender, People *..1 Race)
3 - Go into the Model Browser -> Associations
4 - Right click on your newly created associations, click Properties
5 - Here you need to setup the endpoints for the key and cascade options. Make sure you get the endpoints correct. You can also setup a referential constraint here for your implicit navigational property.
6 - Map the navigational property to the relevant tables/fields.
7 - Validate your model, cross your fingers.
Hope this helps.
Solution 2:
I came across this blog post which proposes the following solution, which worked great for me (unfortunately I could not get RPM1984's to work in my situation).
- Add an Association via designer background right click contextual menu
- Set up your Association (be sure to uncheck creation of foreign key)
- Right click on the association and choose Properties
- Click on the ... button for Referential Constraint
- Set up the relation between the keys within
- Verify (from the designer contextual menu)
- ???
- Profit!