Deleteing entities from a collection

Posts   
 
    
cjmos
User
Posts: 15
Joined: 04-May-2007
# Posted on: 25-Jul-2007 12:39:37   

Hi all,

I have a CartEntity object with a collection if CartDetailEntities (cart.CartDetails). If I run this code:

        public static int DeleteItems(CartEntity cart, List<int> itemIds)
        {
            int deleteCount = 0;
            for(int i = 0 ; i < cart.CartDetails.Count ; i++ )
            {
                if (itemIds.Contains(cart.CartDetails[i].CartDetailId))
                {
                    cart.CartDetails[i].Delete();
                    deleteCount++;
                }
            }
            return deleteCount;
        }

Note: CartDetailEntity is part of a TargetPerEntity hierarchy, which is why I'm not using DeleteMulti().*

I notice that the CartDetailEntitys are deleted from the database but remain in the cart.CartDetails in-memory collection.

Is there anyway I can get the system to both delete the item from the database and remove it from the in-memory collection?

thanks,

Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 25-Jul-2007 16:00:51   

Try:

cart.CartDetails[i].Delete();
cart.CartDetails[i].Remove();
cjmos
User
Posts: 15
Joined: 04-May-2007
# Posted on: 25-Jul-2007 16:08:54   

Surely that would screw up the index of the for loop and you will miss the item after each removed one?

I wondered whether there was some sort of in-built method to update the in-memory collections like cart.CartDetails.RemoveDeletedEntities() or something along those lines.

No worries though, I can quite easily write my own. Suppose I was just being lazy simple_smile .

Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 25-Jul-2007 16:26:16   

Or you can use the following code:

            int count = cart.CartDetails.Count;
            for(int i = 0 ; i <  count; i++ )
            {
                if (itemIds.Contains(cart.CartDetails[i].CartDetailId))
                {
                    cart.CartDetails[i].Delete();
                    cart.CartDetails[i].Remove();
                    count --;
                    i--;
                    deleteCount++;
                }
            }