Delete a child record from the parent collection

2019-03-19 13:11发布

问题:

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?

回答1:

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

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



回答2:

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.



回答3:

I was having the same problem as initforthemoney due to returning a new list as ReadOnly from my collection getter. I found I could continue to use the ReadOnly list by changing the property access strategy of the collection from nosetter to field.



回答4:

I was having a problem where my children elements where returning an Ordered enumerable.

private readonly IList<Child> children;

public virtual IEnumerable<Child> Children { get { return children.OrderBy(c => c.Position); } }

public virtual void DeleteChild(Child item)
{
    children.Remove(item);
}

I moved the ordering to my mapping and returned the children as it is for the IEnumerable. This worked for me!