views:

128

answers:

1

Hi people, 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

A: 

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.

Devart
Hi Devart,I finally got it working by redesigning how things were built.I create the shopping cart first, without any items since I will need to have it saved anyways then, I assign the ShoppingCart ID of the newly created cart to each items I want to create and voila!If I want to add new items, the Cart creation is simply skipped and everything works like a charm and is more separated!But I will try you suggestion in a test project to see if that would be a useful technique later on for other things!Many thanks!
Stéphan