How can I implement a child that has multiple parents in Entity Framework?
The resulting tables must be as follows:
1.Courses:
CourseID int identity
CourseTitle nvarchar
.
.
.
OtherColumns as neede
2.CoursePreRequisites:
CourseID (FK to Course.CourseID)
PreRequisiteCourseID (FK to Course.CourseID)
or is there any better way to achieve multiple parent for a child record?
You just need two navigation properties in the child class refering to the same parent class and – optionally – two corresponding foreign key properties:
If one or both of the two relationships are optional, use
int?instead ofintfor the foreign key properties.If you use the property names as indicated in the example above you don’t need to configure anything. EF will recognize the two one-to-many relationships by naming conventions.
You can also use collections as inverse properties in the
Courseentity if you need or want them:However, in that case you must specify which navigation property pairs belong together in a relationship. You can do this with data annotations for example:
Or with Fluent API: