title: Entity 4.1 Updating an existing parent entity with new child Entities
body: <p>I have an application where you can create a new type of product and add to that product some ingredients. The product and the ingredients are both entities saved in a database. The product entity has a collection of ingredient entities. </p>
  
  <p>(simplified version)</p>
  
  <pre><code>public class Product
     Public Sub New()
       Me.Ingredients = New List(Of Ingredient)()
     End Sub
  
     Property Ingredients as ICollection(Of Ingredient)
  end class
  </code></pre>
  
  <p>When I save the product for the first time, all goes well: I just add it to the context and call SaveChanges.</p>
  
  <pre><code>myDataContext.Products.Add(product)
  myDataContext.SaveChanges()
  </code></pre>
  
  <p>Both the product (parent) and the ingredients (children) are saved and linked to each other. All is well.</p>
  
  <p>However when I add/remove an ingredient to an existing product, I start running into problems. I first clear the existing ingredients collection in the product entity and then add the updated list of ingredients again (I don't re-use ingredients add the moment). I then change the state of the product entity to modified and call savechanges. On the state changing I, however, get the exception "<strong>An object with the same key already exists in the ObjectStateManager</strong>". </p>
  
  <pre><code>myDataContext.Entry(product).State = EntityState.Modified
  </code></pre>
  
  <p>After "some" searching I figured out that the problem is that all the ingredients have a primary key of 0 (as they aren't added yet) and when you change the state of the parent entity (product), all child entities (ingredients) are attached to the context with the key of 0, which causes the problem as the keys are no longer unique.</p>
  
  <p>I have been searching for a solution but can't figure out how to solve this problem. I tried adding the ingredients to the context before changing the state, but then the link between the product and ingredients is missing... How do I update an existing parent entity with new, not yet added child entities? </p>
  
  <p>I use Entity Framework 4.1 and Code First.</p>
  
  <p>Hope you can help me!</p>