sql中的DELETE语句与REFERENCE约束冲突

本文关键字:REFERENCE 约束 冲突 语句 中的 DELETE sql | 更新日期: 2023-09-27 18:03:03

我使用EF代码第一模型。我有三个表,Teacher, StudentAddress。每个教师和学生可以有多个地址,因此Teacher_AddressStudent_Address之间的关联是1到多

我写了:

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; }
} 

Fluent 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();

我可以为TeacherStudent插入数据,没有问题,但当我试图从TeacherStudent中删除任何一行时,它显示以下例外:

DELETE语句与REFERENCE约束"FK_dbo.Address_dbo.Teacher_TeacherId"冲突。冲突发生在数据库"CodeFirst"中。TestContext", table "。地址",列"TeacherId"

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

sql中的DELETE语句与REFERENCE约束冲突

这似乎是一种反向关系。老师和学生不需要参考地址吗?我认为级联将正确工作,如果你删除地址条目(这不是我认为你想要的)。尝试向其他实体添加地址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();