我正在使用 EF 代码优先模型。我有 3 张桌子Teacher
和. 每个教师和学生可以有多个地址,因此 和 之间的关联是1到 many。Student
Address
Teacher_Address
Student_Address
为此,我写道:
public class Teacher
{
public int Id;
public virtual List<Address> Addresses { get; set; }
}
public class Student
{
public int Id;
public virtual List<Address> Addresses { get; set; }
}
public class Address
{
public int Id;
public int? TeacherId { get; set; }
public virtual Teacher Teacher { get; set; }
public int? StudentId { get; set; }
public virtual Student Student { get; set; }
}
流利的API:
//Creating 1 to * relationships b\w Teacher and Address
modelBuilder.Entity<Address>().HasOptional(p => p.Teacher)
.WithMany(p => p.Addresses)
.HasForeignKey(p => p.TeacherId)
.WillCascadeOnDelete();
//creating 1 to * replationship b\w Student and Address
modelBuilder.Entity<Address>().HasOptional(p => p.Student)
.WithMany(p => p.Addresses)
.HasForeignKey(p => p.StudentId)
.WillCascadeOnDelete();
我可以毫无问题地插入数据,Teacher
但是Student
当我尝试删除任何一行时,Teacher
它Student
会显示以下异常:
DELETE 语句与 REFERENCE 约束“FK_dbo.Address_dbo.Teacher_TeacherId”冲突。冲突发生在数据库“CodeFirst.TestContext”、表“dbo.Address”、列“TeacherId”中。
谁能告诉我如何解决这个问题以及我做错了什么?