0

我正在使用 EF 代码优先模型。我有 3 张桌子Teacher和. 每个教师和学生可以有多个地址,因此 和 之间的关联是1到 manyStudentAddressTeacher_AddressStudent_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当我尝试删除任何一行时,TeacherStudent会显示以下异常:

DELETE 语句与 REFERENCE 约束“FK_dbo.Address_dbo.Teacher_TeacherId”冲突。冲突发生在数据库“CodeFirst.TestContext”、表“dbo.Address”、列“TeacherId”中。

谁能告诉我如何解决这个问题以及我做错了什么?

4

1 回答 1

0

好像关系倒退了。老师和学生不应该引用地址吗?我认为如果您删除地址条目(这不是我认为您想要的),级联将正常工作。尝试将地址 ID 添加到其他实体,看看删除是否有效。

像这样的东西:

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;

} 

流畅的api:

modelBuilder.Entity<Teacher>().HasMany(p => p.Addresses)
                                  .WillCascadeOnDelete();
于 2013-03-09T19:23:33.080 回答