【发布时间】:2011-09-07 06:20:09
【问题描述】:
将 EF4 中的关联视为:
孩子 1----0..1 父母
因此,在 Parent 中对于 Child 有一个不可为空的外键。
我创建了一个新的父级并分配了一个现有的子级。不幸的是,这是一个有点奇怪的家庭,因为有 300 位父母,其中许多人共享同一个孩子。
当我尝试保存 300 条父记录时,遇到了 UpdateException:
“MyEntities.Parents”中的实体参与“子” 关系。找到 0 个相关的“孩子”。预计有 1 个“孩子”。
这里有一些代码来说明:
// 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();
}
我不知道如何绕过它。我想保存一个引用现有子代的新父代。
谢谢,
理查德
【问题讨论】: