locked
Add child to existing parent record in entity framework. RRS feed

  • Question

  • 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.



     
    Thursday, April 15, 2010 2:03 AM

Answers

  • You are adding the entity twice in fact. Try the following code to add the entity:
      static void SaveEntity(Entity entity) {
        if (entity == null)
         throw new ArgumentNullException("entity");
        if (entity.EntityKey == null) {
         context.AddToEntities(entity);
        }
        context.SaveChanges();
      }
    

    Devart Team
    http://www.devart.com/dotconnect
    ADO.NET data providers for Oracle, MySQL, PostgreSQL, SQLite with Entity Framework and LINQ to SQL support
    Thursday, April 15, 2010 2:36 PM