Removing and deleting a child item

Nov 15, 2008 at 10:11 PM

Thanks for all your hard work on this project.  Its saved me a lot of headache.

I'm having some difficulties with the following scenario.  I have a Cart table which has a 1 to many relationship with a CartItem table.  Now when I need to remove a CartItem from the cart, I would also like to delete the CartItem record from the database. 

Calling cart.CartItems.Remove(cartItem); seems to only set the CartId field in that table to null, so I need to also call the SetAsDeleteOnSubmit on the CartItem. 

I tried calling the cartItem.SetAsDeleteOnSubmit() method before and after calling the Remove.  If I called it before, the LINQEntityState property would be changed from Deleted to Detached by the Remove method, resulting in the delete operation being lost.  CartId would become null in the CartItem table but the record was not deleted.  If I called SetAsDeletedOnSubmit() after the Remove, it would throw an error saying that the CartItem was detached and could not be set to Deleted. 

I'm not sure if the above is intended behavior.  If it is, do you have any suggestions on how I could get around it?

Thanks again for all your work.


Nov 15, 2008 at 11:25 PM
Hi there,

The "remove" feature in Linq 2 Sql is more of a "detach" rather than a delete, this is not what you want to use - basically it removes the relationship between a parent and one of it's children in a collection - similar to setting a child object to null in a 1 to 1 relationship - it does not actually deelete the record at the end of the day.  You should not be calling this at all for a delete.

I'm assuming you want to delete the object but hide it from any lists on your displays or perhaps in some business logic - which make total sense, but from database point of view you wouldn't do two operations (a delete and a detach) to acheive this outcome, it just wouldn't make sense - as when the object is deleted, there's not much sense in detaching or visa versa for the purposes of deleting the object. 

It's also really down to the way Linq 2 Sql works in a detached scenario - one operation at a time on a single entity between round trips to the database - of course you can update multiple objects in one submit, but you can only attach an object for one operation once (i.e. create, delete, update).

My suggestion is, if you want to delete an object and you want to filter it out of any processing or displays, use SetAsDeleteOnSubmit() and then filter out the unwanted records by checking the EntityState Value != Deleted, something like so:

cart.cartitems.Where( x => x.EntityState != EntityState.Deleted);

Anyway, hope I've helped.


Nov 16, 2008 at 12:32 AM
Ok I understand now.  Thank you very much.  I really appreciate your help on this.