I have parent child relationship between two entities(Parent and Child).
My Parent mapping is as follows:
<class name="Parent" table="Parents">
...
<bag name="Children" cascade="all">
<key column="ParentID"></key>
<one-to-many class="Child"></one-to-many>
</bag>
</class>
I would like to execute the following:
someParent.Children.Remove(someChild);
The Child class has a reference to another parent class, Type. The relationship looks like
http://yuml.me/diagram/scruffy/class/%5BParent%5D+1-%3E*%5BChild%5D%2C%20%5BType%5D+1-%3E*%5BChild%5D
Note: I apologize for the non-linked url above, I couldn't seem to get past the asterisk in the url string using Markup
Due to this relationship, when the above code is called, instead of a DELETE query, an UPDATE query is generated which removes the ParentID from the Child table(sets to null).
Is it possible to force NHibernate to delete the child record completely, when removed from the Parent.Children collection?
UPDATE
@Spencer's Solution
Very attractive solution as this is something that can be implemented in future classes. However, due to the way sessions are handled(in my particular case) in the repository pattern, this is near impossible as we would have to pass session types(CallSessionContext/WebSessionContext) depending on the application.
@Jamie's Solution
Simple and quick to implement, however I've hit another road block. My child entity looks as follows:
When using the new method, NHibernate generates an update statement setting the TypeID and ParentID to null, as opposed to a single delete outright. If I missed something within the implementation, let me know as this method would be painless to move forward with.
@The One-Shot-Delete solution described here, outlines an idea dereferencing the collection to force a single delete. Same results as above however, an update statement is issued.
//Instantiate new collection and add persisted items
List<Child> children = new List<Child>();
children.AddRange(parent.Children);
//Find and remove requested items from new collection
var childrenToRemove = children
.Where(c => c.Type.TypeID == 1)
.ToList();
foreach (var c in childrenToRemove) { children.Remove(m); }
parent.Children = null;
//Set persisted collection to new list
parent.Children = Children;
Solution
Took a bit of digging, but Jamie's solution came through with some additional modifications. For future readers, based on my class model above:
Type mapping - Inverse = true, Cascade = all Parent mapping - Inverse = true, Cascade = all-delete-orphan
Remove methods as described in Jamie's solution works. This does produce a single delete statement per orphaned item, so there is the possibility for tuning in the future, however the end result is successful.