Gary Brunton
Gary Brunton

Reputation: 1960

Nhibernate: Delete orphan children but don't delete children when parent is deleted

I'm looking for a way to configure nhibernate so that orphan children entities are deleted automatically but if a parent is deleted and a child exists, a delete query on the parent is executed but not for the children. Basically I would like to set up my cascade option to be "save-update-orphan" but this is not supported.

    <set name="children" inverse="true" cascade="all-delete-orphan" access="field">
        <key column="ParentId" />
        <one-to-many class="Parent" />
    </set>

The all-delete-orphan doesn't work for me because it deletes the children automatically when the parent is deleted.

Update To try and be more clear... When I explicitly remove the child from the parent's collection, I want the child deleted. When I explicitly delete the parent, I don't want the children deleted.

Upvotes: 4

Views: 2840

Answers (2)

Hace
Hace

Reputation: 1421

Well, You should be deleting the childobject if that is the one you want to delete. That is, do not try to delete the child via the parent if you do not want the parent to be deleted.

Upvotes: 0

Iain
Iain

Reputation: 11262

I don't believe you can do what you want via configuration.

The only option I can think of is turn off orphan delete, and manually delete the child when you want it deleted.

NHibernate Cascades: the different between all, all-delete-orphans and save-update

Here is what each cascade option means:

  • none - do not do any cascades, let the users handles them by themselves.
  • save-update - when the object is saved/updated, check the assoications and save/update any object that require it (including save/update the assoications in many-to-many scenario).
  • delete - when the object is deleted, delete all the objects in the assoication.
  • delete-orphan - when the object is deleted, delete all the objects in the assoication. In addition to that, when an object is removed from the assoication and not assoicated with another object (orphaned), also delete it.
  • all - when an object is save/update/delete, check the assoications and save/update/delete all the objects found.
  • all-delete-orphan - when an object is save/update/delete, check the assoications and save/update/delete all the objects found. In additional to that, when an object is removed from the assoication and not assoicated with another object (orphaned), also delete it.

Upvotes: 4

Related Questions