tags:

views:

21

answers:

2

I've got

class Parent
{
    IList<Child> Children;
}

class Child
{
}

When deleting a Child I need to remove all references to it from any Parents that reference it.

How can I do this in NHibernate?

There is no Parent FK on Child, the relationship is stored in a 3rd "link" table

Thanks

+1  A: 

To make this happen, there needs to be a relationship of some sort, starting from the Child Entity.

Then you can simply use cascade-delete to its 3d (I'm guessing this is a many-to-many) table.

Bertvan
ah youre right, it is a man-to-many. doh! is there a way to do it without having the relationship mapped on the child end? having it there doesnt make sense in my domain. i guess i could make it private but it feels like a hack
Andrew Bullock
It seems like it does make sense in your domain, since you need an action to happen on its delete... I would simply add it to the mappings. If you really don't want to do that, maybe you can set the cascades on your FK in the DB...
Bertvan
+2  A: 

This is not a parent-child relation. Children have only one parent (the belong to the parent). This is a many-to-many relation between independent entities. This is a important difference.

You can't actually remove the "children" from the "parent" directly in HQL the way it is designed now. This are your options:

  • load the "parents" into memory and remove the "child" from the list.
  • Add a reference from the "child" back to the "parents". Make the other relation inverse. It should actually automatically remove the item in the link table when you remove a "child", because the link would belong to the "child" then.
  • Delete the link using native SQL. This is not nice, but also not too bad because it is trivial standard sql.
Stefan Steinegger
yeah i realise its a mant-to-many, was being daft. Ive added a property to `Child` but simply made it private to enable deletes to automatically tidy themselves up without exposing the collection
Andrew Bullock