The Relationship_ID
stems from the Relationship.RelatedPersons
collection. I think it's not correct to have a collection here, instead it should be a single reference RelatedPerson
(singular) since a single Relationship
entity describes the relationship between exactly two people, not between a person and a collection of other people. So, I'd propose to change the model like this:
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
[InverseProperty("Person")]
public virtual ICollection<Relationship> Relationships { get; set; }
}
public class Relationship
{
public int ID { get; set; }
public RelationshipType DependencyType { get; set; }
[ForeignKey("Person")]
public int PersonID { get; set; }
public virtual Person Person { get; set; }
[ForeignKey("RelatedPerson")]
public int RelatedPersonID { get; set; }
public virtual Person RelatedPerson { get; set; }
}
The [InverseProperty]
attribute is important here to tell EF that Relationship.Person
is the inverse navigation property of Person.Relationships
. Without that attribute you would get three foreign keys in the Relationship
table refering to the Person
table.
You probably also need to disable cascading delete for one of the relationships to avoid an exception about forbidden multiple cascading delete paths from Person
to Relationship
. It can be done with Fluent API:
modelBuilder.Entity<Relationship>()
.HasRequired(r => r.RelatedPerson)
.WithMany()
.HasForeignKey(r => r.RelatedPersonID)
.WillCascadeOnDelete(false);
Once you have that you can add the second relationship with Fluent API as well which would allow you to remove all attributes from the model as they are redundant then:
modelBuilder.Entity<Relationship>()
.HasRequired(r => r.Person)
.WithMany(p => p.Relationships)
.HasForeignKey(r => r.PersonID);