Delete a child record from the parent collection

initforthemoney picture initforthemoney · Jun 12, 2009 · Viewed 11.9k times · Source

I'm developing a sample application so that I can learn the ins and outs of NHibernate. I am struggling with a delete issue. I wish to be able to delete a child record by removing it from its parent’s collection and then saving the parent. I have setup a bidirectional one-to-many relationship and inserting/updating is working great.

Here are my mappings

Basket:

<bag name="Items" inverse="true" cascade="all"> <key column="BasketId" /> <one-to-many class="BasketItem" /> </bag>

BasketItem:

<many-to-one not-null="true" name="Basket" column="BasketId" />

I would like to call basket.RemoveBasketItem(BasketItem item) then Session.SaveUpdate(basket) so that the basket item will be deleted. Is this possible?

Answer

mookid8000 picture mookid8000 · Jun 12, 2009

Change cascade="all" into cascade="all-delete-orphan".

cascade="all" will only delete your child records if the parent gets deleted.