Add child to existing parent record in entity framework.

Posted by Shawn Mclean on Stack Overflow See other posts from Stack Overflow or by Shawn Mclean
Published on 2010-04-11T20:26:55Z Indexed on 2010/04/11 20:33 UTC
Read the original article Hit count: 292

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:

alt text

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.

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about entity-framework