I’m trying to model what seems like a relatively simple referral scenario. I’ve tried to search but I’m not exactly sure what the name is for the kind of relationship I am looking to create.
Here is the explanation:
One student can refer another student to the school. Therefore each student can refer many students and each new student can only be referred by one existing student.
Here is the code:
// Model
public class Student
{
public int? ReferralID { get; set; }
public virtual Referral Referral { get; set; }
public virtual ICollection<Referral> Referrals { get; set; }
}
public class Referral
{
public int ReferringStudentID { get; set; }
public virtual Student ReferringStudent { get; set; }
public int ReferredStudentID { get; set; }
public virtual Student ReferredStudent { get; set; }
}
// Context
modelBuilder.Entity<Student>()
.HasOptional(x => x.Referral)
.WithMany()
.HasForeignKey(x => x.ReferralID);
modelBuilder.Entity<Student>()
.HasMany(x => x.Referrals)
.WithRequired(x => x.ReferringStudent)
.HasForeignKey(x => x.ReferringStudentID);
Here is the resulting database:

Question:
What can I do to get Entity Framework to recognize that ReferringStudentID should be a foreign key? I’ve tried using the fluent API to describe the relationship from the Referral to the Student but the results are the same. Am I doing something wrong?
Thanks in advance! 🙂
The problem is EF tries to create foreign keys with cascade deletes. Your referral table has two not nullable foreign keys to student table. That will form multiple delete paths if you delete a student. This is not allowed by SQL Server.
Change your foreign key mapping with
ReferringStudentIDas followsYou need to think how you are going to keep referential integrity if you allow to delete students.