2012-04-15 50 views
0

我有4個表,像這樣的:經與EF流利的API困難

public class Table1 
{ 
public int Id {get;set;} 
public string Name {get;set;} 
} 

public class Table2 
{ 
public int Id {get;set;} 
public string Name {get;set;} 
public int Table1Id {get;set;} 
public virtual Table1 {get; set;} 
} 

public class Table3 
{ 
public int Id {get;set;} 
public string Name {get;set;} 
public int Table2Id {get;set;} 
public virtual Table2 {get; set;} 
} 

public class Table4 
{ 
public int Id {get;set;} 
public string Name {get;set;} 
public int Table3Id {get;set;} 
public virtual Table3 {get; set;} 
} 

而且我一口流利的API就像這樣:

modelBuilder.Entity<Table2>().HasRequired(x => x.Table1).WithMany().WillCascadeOnDelete(false); 
modelBuilder.Entity<Table3>().HasRequired(x => x.Table2).WithMany().WillCascadeOnDelete(false); 
modelBuilder.Entity<Table4>().HasRequired(x => x.Table3).WithMany().WillCascadeOnDelete(false); 

當我嘗試種子的表,我得到這個錯誤:

INSERT語句衝突與外鍵約束「FK_Table4_Table3_Table3Id 衝突發生於數據庫MYDB,標籤le「dbo.Table3」,'Id'這一列。聲明已被終止。「

我看不到我要去的地方錯了

+0

您能否顯示「*當我嘗試播種表格*」的代碼? – Slauma 2012-04-15 17:21:58

回答

1

做到這一點...

modelBuilder.Entity<Table2>() 
    .HasRequired(t => t.Table1) 
    .WithMany() // t => t.AllTable2s) 
    .HasForeignKey(t => t.Table1ID); 

...和所有make it compile以上! :)(例如public virtual Table1 {get; set;}轉換爲public virtual Table1 Table1 {get; set;}