2011-09-07 111 views
0

考慮EF4關聯爲:附加現有實體到新建實體(1-1關係)

兒童1個---- 0..1父

所以,有一個非空的外鍵父母爲孩子。

我創建一個新的Parent並指定一個現有的孩子。不幸的是,這是一個有點陌生的家庭,因爲有300名父母,許多人分享同一個孩子。

當我試圖挽救300條父記錄,我遇到一個UpdateException:

實體在「MyEntities.Parents」參加「少年」 關係。 0個相關的「孩子」被發現。預計會有'小孩'。

下面是一些代碼來說明:

// scope autosaves 
using (new UnitOfWorkScope(true)) 
{ 
    var allParents= (from DataRow dataRow in this.dataTable.Rows 
        where dataRow != null 
        select CreateParent(dataRow) 
        into parents 
        where parents != null 
        select parents).ToList(); 

    var parentFacade = new ParentFacade(); 

    foreach (var newParent in allParents) 
    { 
     parentFacade.Add(newParent); 
    } 
} 

private static Parent CreateParent(DataRow dataRow) 
{ 
    var parent = new Parent 
    { 
     SomeProperty = 'Moo', 
     Child = GetChild(someValue) 
    } 

    return Parent; 
} 

private static Child GetChild(string someValue) 
{ 
    return new ChildFacade().GetChild(someValue); 
} 

// Facade 
public Child GetChild(string someValue) 
{ 
    return (from c in this.ObjectContext.Children 
      where c.SomeProperty == someValue 
      select c).FirstOrDefault(); 
} 

我無法弄清楚如何繞過它。我想通過引用現有的孩子來保存新的父母。

感謝,

理查德

回答

0

許多共享相同的孩子。

你的關係不能是1 - 0..1,而是一個父母可以有很多孩子的人。您目前的關係表示Child有可選ParentParent必須有Child

+0

但是,如果下拉提供單一選擇,那麼只能有一個選擇,因此只有一個孩子?那麼我需要的是1-1嗎?有時候,把關係放在數據庫中會更容易,然後把它吸回來:) – Richard

+0

知道了。它確實是從孩子到父母的一對多,然後外鍵設置好。找到你的博客條目的外國與獨立關係的主題,並發現它非常有啓發性。保持良好的工作!很好。 – Richard