2011-09-07 109 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