我正在使用EF代码第一个模型。我有3个表Teacher
,Student
和Address
。每位教师和学生都可以拥有多个地址,因此Teacher_Address
和Student_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; }
}
流利的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'。
有人可以告诉我如何解决这个问题以及我做错了什么?
答案 0 :(得分: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();