Reputation: 1409
I am building an application with many different objects (tables), many of which have a need to have a one-to-many relationship to an "Attribute" object. For example, I could have five different objects - A, B, C, D, E - and each of these needs to have an Attributes property - A.Attributes, B.Attributes, etc.
My question is, how would be the best way to structure this in EF Code First? This Attribute class may end up having 15-20 different classes that have a relationship with it.
Currently, a configuration for one of the "parent" classes looks like this:
HasMany(rdp => rdp.Attributes)
.WithOptional()
.WillCascadeOnDelete();
However, this will create a foreign key column on the Attribute table (e.g., "A_Id", "B_Id", etc). So if I have 20 different classes with attributes, the Attribute table will have 20 different foreign keys.
Is there any better way to structure this?
Upvotes: 3
Views: 931
Reputation: 11568
You could introduce an AttributeList type that maps to its own table. I.e. you could model the list as an entity.
A, B, C, D, E would have a one-to-one association to the AttributeList, with the foreign key to the AttributeList on the A, B, C, D and E classes.
Each AttributeList object contains many attributes, or in other words there is a one-to-many relationship from AttributeList to Attribute.
Now you have a single type with one-to-many to the Attributes and you only need a single foreign key to the AttributeList on the attributes.
Upvotes: 2