Reputation: 22906
I am trying to achieve the following end result. My Person entity needs a collection of extra values and this collection of values will vary from Person instance to instance. I also have another Contact entity that likewise can have extra values form instance to instance.
Therefore I need three tables, a Person, Contact and an Extra where the Extra has the set of extra values for each Person and Contact instance that needs extra values. By giving the Person and Contact a GUID field it means that the GUID values will be unique across both tables and so I can use that as the field to join on. So I expect the definition to look like this...
Person
Id - int - Primary Key
Instance - GUID - Unique Constraint
Contact
Id - int - Primary Key
Instance - GUID - Unique Constraint
Extra
Id - int - Primary Key
Instance - GUID
Value - string
But I cannot model this into Entity Framework. I would like my Person and Contact entities to have a collection each that is the set of Extra values that are relevant to that entity. I create the three tables with the set of columns as indicated above.
But I cannot get the association to work as expected, it always wants to add extra columns to the database based on the primary key of the Person and Contact entities. Any ideas how to actually get this to work? Or maybe this is not possible in EF?
Upvotes: 0
Views: 694
Reputation:
As answered already, EF does not support unique keys. However, if you don't actually need to do anything with the Id
property, it may suffice to tell EF that Instance
is the primary key. EF doesn't really care whether it's the primary key at the database level, it merely needs to know whether it can use it as a key itself.
Edit: actually, that still wouldn't work. Besides not supporting unique keys, your Extra.Instance
does not correspond to any fixed entity. In order to get it working, you would need to split the Extra
table into PersonExtra
and ContactExtra
tables. That's probably a good idea regardless, as it allows you to add the foreign key constraints at the database level that correspond to those you wish to see in EF.
Upvotes: 1
Reputation: 19393
The EF way of doing this is to use a linking table - a simple table that has two columns, which will be not be visible in your model directly but the collections will be.
e.g.
Person
Id - int - Primary Key
Instance - GUID - Unique Constraint
Contact
Id - int - Primary Key
Instance - GUID - Unique Constraint
Extra
Id - int - Primary Key
Instance - GUID
Value - string
PersonExtra
PersonId - int
ExtraId - int
ContactExtra
ContactId - int
ExtraId - int
or change your Primary Key to be the GUID if your model will permit this.
Upvotes: 0
Reputation: 364279
This is not possible with EF because it doesn't support unique keys. Only primary keys can be used as principal in relation.
Upvotes: 2