views:

302

answers:

1

I have a table [User] and another table [Salesperson] in my database. [Salesperson] defines a unique UserID which maps to [User].UserID with a foreign key. When I generate the model with Entity Framework I get a 1-to-Many relationship between [User]-[Salesperson], meaning that each User has a "Collection of Salesperson", but what I want is a 0..1-to-1 relationship where each User has a nullable reference to a "Salesperson".

I tried fiddling around with the XML and changing the association's multiplicity settings, but that only produced build errors. What I am trying to achieve is no different than having a nullable SalespersonID in [User] that references [Salesperson].SalespersonID, but because salespeople only exist for specific users it feels like I'd be muddying up my [User] table structure just to get the relationship to point the right way in Entity Framework.

Is there anything I can do to change the multiplicity of the relationship?

+1  A: 

Make the PK of Salesperson itself a FK to User. The EF's GUI designer will then get the cardinality correct, since PKs are unique.

Craig Stuntz
You can call it SalespersonId if you like, but because of the FK Salesperson.SalespersonId == User.UserId, regardless of what it's called. The GUI designer can then infer the correct cardinality, and the DB will enforce it.
Craig Stuntz
I haven't tested this yet, but once I do I'll mark the answer (assuming it works!). Thanks a ton. :)
Nathan Taylor
Was there an existing relationship before you regenerated? Try it on a new table. This *does* work for us. Also, if User.UserId is not the PK, try it with the PK. It's possible the EF's GUI designer can see the PK but not the unique constraint.
Craig Stuntz
Success. I had to regenerate the context, but it worked. :)
Nathan Taylor
I noticed that EF emits no different code if there is a uniqueness constraint than it does if there is not one. Seems odd...
Nathan Taylor
Theory: The relationship is in the client schema, which is only updated (and even then in small pieces) when the store schema changes "significantly". The idea is to preserve your changes, which can include changes to relationships. The store schema is always regenerated from scrach. The change in the store schema here might not be detected (by the GUI) as "significant" enough to cause mutating the client schema, again, to try and preserve changes you might have made. But when you regenerate it picks up the constraint in the store schema.
Craig Stuntz