NHibernate StaleObjectStateException when using optimistic version optimization on an object with a one-to-many relationship
I am using NHibernate and ASP.Net, using a session per request as suggested in the Billy McCafferty best practices article (sorry I cannot include a link). I have used this successfully with optimistic version locking by saving the updated entities to the HTTP session object and reconnecting to the NHibernate session using the SaveOrUpdate method.
However, my final page requires an update of the collection of child objects. I used the method suggested in the parent child example of the NHibernate tutorial (chapter 17). This works when loading and saving in one request. However, when loaded in one request, saved in the HTTP session and reconnected in a subsequent request using SaveOrUpdate, I get a StaleObjectException when clearing the NHibernate session. This happens even if there have been no changes to the collection of child objects.
Changes made to properties of the parent object are persisted to the database, so NHibernate appears to be trying to update the object twice. I suspect it has something to do with the cascade parameters in the mapping, but they are necessary for the correct parent / child relationship.
Here are my mapping files:
Displaying the parent class
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="NHS.WebTeam.PharmacyFirst.Medication, PharmacyFirst" table="Medication" lazy="false" optimistic-lock="version" where="Deleted=0">
<id name="ID" column="Medication_ID" unsaved-value="0">
<generator class="identity" />
</id>
<version column="version" name="Version"/>
<property name="Deleted" column="Deleted" />
<property name="Name" column="Name" />
<bag name="Prices" access="field.camelcase-underscore" lazy="false" inverse="true" cascade="all">
<key column="Medication_ID"/>
<one-to-many class="NHS.WebTeam.PharmacyFirst.MedicationPrice, PharmacyFirst" />
</bag>
</class>
</hibernate-mapping>
Displaying child classes
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="NHS.WebTeam.PharmacyFirst.MedicationPrice, PharmacyFirst" table="Medication_Price" lazy="false" optimistic-lock="version" where="Deleted=0">
<id name="ID" column="Medication_ID" unsaved-value="0">
<generator class="identity" />
</id>
<many-to-one name="Medication" column="medication_id" not-null="true" cascade="none"/>
<property name="DateFrom" column="Date_From" />
<property name="Price" column="Price" />
</class>
</hibernate-mapping>
Please help someone.
a source to share