I’ve been digging in the posts in here and on google and couldn’t find anything helping me to solve a problem I have with saving children entities on an existing entity.
Let’s say I have a shopping cart that will hold items, that means I have a ShoppingCart entity which has ShoppingCartItem entity collection.
In my controller, I check if the ShoppingCart exists and retrieve the entity if there’s one. If not, it’s a new entity (Entitystate is marked as Added).
Then, I continue by adding items to the already existing collection (if any items are in there already)
My problem right now is ONLY when I save changes to an already created ShoppingCart:
It’s adding a NEW Shopping cart in the database with both the existing items AND the new items…
So, if I have one Shoppingcart and two children and I now add 3 new items, I end up with 2 ShoppingCart entries in the ShoppingCart table and 7 ShoppingCartItem entries…
I traced the code and, the ShoppingCart entity is getting marked as Added as soon as a new ShoppingCartItem is added using AddObject()…
How can I prevent that?
Thanks a lot,
Stéphan
The simplest solution is to retreive the existing ShoppingCart with detail entities, and then not to perform any AddObject calls. Call the SaveChanges() method instead, this will write the changes to the database without creating a new ShoppingCart entity.