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.
(simplified version)
public class Product
Public Sub New()
Me.Ingredients = New List(Of Ingredient)()
End Sub
Property Ingredients as ICollection(Of Ingredient)
end class
When I save the product for the first time, all goes well: I just add it to the context and call SaveChanges.
myDataContext.Products.Add(product)
myDataContext.SaveChanges()
Both the product (parent) and the ingredients (children) are saved and linked to each other. All is well.
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 "An object with the same key already exists in the ObjectStateManager".
myDataContext.Entry(product).State = EntityState.Modified
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.
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?
I use Entity Framework 4.1 and Code First.
Hope you can help me!