1 min read

1..0 or 1 relationships in Entity Framework

I came across this problem today when migrating a project from VS 2008/.NET 3.5 to VS 2010 RC1/.NET 4.0. I don’t actually think it’s a VS 2010 thing, though.

I have two entities A and B. There is a navigation property on A, and it can have either one or no instances of B. B’s foreign key is to A’s primary key (obviously) but B also has its own primary key. In the database, B has a unique index on that foreign key column, which will enforce the rule.

The problem when upgrading to VS 2010 occurred because I clicked the “Include foreign key columns in the model” check box when generating the model from the database. (I regenerated it because the tools might be better in 2010 so figured I should start from scratch.) That’s where my problem came from. The entity model designer wouldn’t let me change the navigation property and associated relationship from 1..* to 1..0 or 1, because the relationship had to be between the entities’ keys for that to work.

The problem only happens when you generate the model with foreign keys as their own columns. I regenerated it so that foreign key columns weren’t generated (the foreign keys were represented only as their navigation properties) and it worked fine, as it did in VS 2008.

I found this answer here: http://stackoverflow.com/questions/2141328/unique-keys-not-recognized-by-entity-framework/2326859#2326859

Hopefully this might be of some help to someone else!