Delete a child record from the parent collection

被刻印的时光 ゝ 提交于 2019-12-03 17:35:16

问题


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!



来源:https://stackoverflow.com/questions/986045/delete-a-child-record-from-the-parent-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!