Add child to existing parent record in entity framework.
- by Shawn Mclean
My relationship between the parent and child is that they are connected by an edge. It is similiar to a directed graph structure.
DAL:
public void SaveResource(Resource resource)
{
context.AddToResources(resource); //Should also add children.
context.SaveChanges();
}
public Resource GetResource(int resourceId)
{
var resource = (from r in context.Resources
.Include("ToEdges").Include("FromEdges")
where r.ResourceId == resourceId
select r).SingleOrDefault();
return resource;
}
Service:
public void AddChildResource(int parentResourceId, Resource childResource)
{
Resource parentResource = repository.GetResource(parentResourceId);
ResourceEdge inEdge = new ResourceEdge();
inEdge.ToResource = childResource;
parentResource.ToEdges.Add(inEdge);
repository.SaveResource(parentResource);
}
Error: An object with the same key already exists in the ObjectStateManager. The existing object is in the Unchanged state. An object can only be added to the ObjectStateManager again if it is in the added state.
Image:
I have been told this is the sequence in submitting a child to an already existing parent:
Get parent - Attach Child to parent - submit parent.
That is the sequence I used. The code above is extracted from an ASP.NET MVC 2 application using the repository pattern.