Attaching Existing Entity to New Entity (1-1 Relationship)
Consider an association in EF4 as:
Child 1----0..1 Parent
So, there's a non nullable foreign key in Parent for the Child.
I create a new Parent and assign an existing child. Unfortunately, this is a somewhat strange family as there are 300 parents, many sharing the same child.
When I try to save the 300 parent records, I encounter an UpdateException:
Entities in 'MyEntities.Parents' participate in the 'Child' relationship. 0 related 'Child' were found. 1 'Child' is expected.
Here's some code to illustrate:
// 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
开发者_StackOverflow 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();
}
I can't figure out how to get around it. I want to save a new parent with a reference to an existing child.
Thanks,
Richard
many sharing the same child.
Your relation cannot be 1 - 0..1 but one to many where one parent can have many children. Your current relation says that Child
has optional Parent
and Parent
must have a Child
.
精彩评论