views:

2860

answers:

2

Hi,

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?

+6  A: 

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

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

mookid8000
When my RemoveBasketItem looks like this: this.basketItems.Remove(itemToRemove); I get this error: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: Basket.Items
Sounds like you somehow overwrote the `IList` reference holding your basket items. You can only put your own implementation of `IList` in there when the list reference is null - if you load a basket from the DB, NH will put its own `PersistentBag` as the `IList` implementation - and you must leave this reference alone for cascade to work properly.
mookid8000
I got it to work! Thanks for your help :-) I was having problems because my basket.Items property was newing up a read-only List. Now I am simply returning the private instance of my items.
This change means my basket items could be modified by client code :-( basket.Items.Add(). I will need to look into this a bit more.
I usually make AddItem/RemoveItem methods, and then have my property return only an IEnumerable<Item> - this way, the consuming code must new up their own List or whatever they want to do, and they never accidentally modify the persistent list.
mookid8000
A: 

I have same scenario and ive used cascade="all-delete-orphan" in bagList but when i delete a single child item in a collection it deletes the parent object as well.

Muhammad Usman Iqbal
Make sure your child object has cascade="none"
jalchr