0
我正在使用EF代碼的第一個模型。我有3個表Teacher
,Student
和Address
。每個老師和學生可以有多個地址,因此Teacher_Address
和Student_Address
之間的關聯是1到很多。DELETE語句與sql中REFERENCE約束衝突?
爲此,我寫道:
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'發生衝突。
任何人都可以請告訴我如何解決這個問題,我做錯了什麼?