Delete a child record from the parent collection

2019-03-19 12:59发布

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?

4条回答
淡お忘
2楼-- · 2019-03-19 13:22

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楼-- · 2019-03-19 13:23

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

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

查看更多
4楼-- · 2019-03-19 13:30

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!

查看更多
Evening l夕情丶
5楼-- · 2019-03-19 13:33

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.

查看更多
登录 后发表回答