2013-03-09 80 views
0

我正在使用EF代碼的第一個模型。我有3個表Teacher,StudentAddress。每個老師和學生可以有多個地址,因此Teacher_AddressStudent_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沒有問題,但是當我試圖刪除任何一個排出來的TeacherStudent則顯示以下例外情況:

DELETE語句與REFERENCE約束「FK_dbo.Address_dbo.Teacher_TeacherId」衝突。數據庫「CodeFirst.TestContext」,表「dbo.Address」,列'TeacherId'發生衝突。

任何人都可以請告訴我如何解決這個問題,我做錯了什麼?

回答

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(); 
相關問題