I'm new to nHibernate, and trying to get my head around the proper way to update detached objects from a web application form POST. (We're using ASP.NET MVC)
The object I'm trying to update contains (among other things) an IList of child objects, mapped something like this:
<bag name="PlannedSlices" inverse="true" cascade="all-delete-orphan">
<key column="JobNumber" />
<one-to-many class="SliceClass" />
</bag>
We have arranged our MVC edit view form so that when it's posted back, our action method is passed am object (incluing the List<> of child items. We round-trip all the entity ID's correctly via the form.
Our naive attempt at the post action method does a session.SaveOrUpdate(parentObject), with the parentObject which has been scraped from view form by the default modelbinder.
This seems to work fine for any of the following scenarios:
- Creating a new parent object
- Modifying the parent's properties
- Adding new child objects
- Modifying existing child objects (Looking at nHibernate logs, I can see it correctly establishing if the objects are new or existing, and issuing the appropriate UPDATE or INSERT)
The scenario which fails is: - Deleting child objects - i.e if they're not in the IList, they don't get deleted from the database. There's no exception or anything, they just don't get deleted.
My understanding is that this is because the magic which nHibernate performs to create a list of children which require deletion doesn't work with detached instances.
I have not been able to find a simple example of what this sort of action method should look like with nHibernate (i.e. using a model-binder object as a detached nHibernate instance) - examples based on MS EF (e.g. http://stephenwalther.com/blog/archive/2009/02/27/chapter-5-understanding-models.aspx) seem to use a method 'ApplyPropertyChanges' to copy changed properties from the model-bound object to a re-loaded entity instance.
So, after all that, the question is pretty simple - if I have the model binder give me a new object which contains collections of child objects, how should I update that via nHibernate, (where 'update' includes possibly deletion of children)?