2012-11-06 38 views
3

基本上我試圖實現的是我有三個表,其中一個父項將始終有一個條目,而其他兩個表中只有一個將被填充。該說我處理的複雜性,對於表的主鍵是兩個字段實體框架代碼組合鍵上的第一對一關係

ParentTable 
----------- 
UniqueID 
OwnerID 
[Some more fields] 


ChildTable1 
----------- 
UniqueID 
OwnerID 
[Some more fields] 


ChildTable2 
----------- 
UniqueID 
OwnerID 
[Some more fields] 

我不知道是否有人對如何最好地通過最好用流利的EF代碼第一次做到這一點的任何建議的組合API。

回答

7

你只需要定義主鍵是複合...

modelBuilder.Entity<Parent>().HasKey(p => new { p.UniqueID, p.OwnerID }); 
modelBuilder.Entity<Child1>().HasKey(c => new { c.UniqueID, c.OwnerID }); 
modelBuilder.Entity<Child2>().HasKey(c => new { c.UniqueID, c.OwnerID }); 

...然後定義兩個一比一的關係:

modelBuilder.Entity<Parent>() 
    .HasOptional(p => p.Child1) 
    .WithRequired(); // or .WithRequired(c => c.Parent) 

modelBuilder.Entity<Parent>() 
    .HasOptional(p => p.Child2) 
    .WithRequired(); // or .WithRequired(c => c.Parent) 

不能定義儘管有一個約束(除了可能通過在數據庫中定義觸發器),這可以確保給定的父親只能引用兩個孩子中的一個,但不能同時引用這兩個孩子。您必須在應用程序的業務邏輯中處理這個限制。

相關問題