views:

1086

answers:

1

I am using NHibernate and ASP.Net using a session per request as suggested in the best practices article by Billy McCafferty (sorry, I cannot include the link). I have used this successfully with version optimistic locking, saving updated objects in the HTTP Session object and reattaching to the NHibernate session using the SaveOrUpdate method.

However, my latest page requires the update of a collection of child objects. I used the method suggested in the parent child example of the NHibernate manual (Chapter 17). This works when loaded and saved in a single request. However, when loaded in one request, saved in the HTTP Session, and reattached in a subsequent request using SaveOrUpdate, I get a StaleObjectException when flushing the NHibernate session. This happens even if no changes are made to the child object collection.

Changes that are made to the parent object's properties are saved to the database, so it would appear that NHibernate is trying to update the object twice. I suspect that this is something to do with the cascade options in the mapping, but these are required in order to get the parent/child relationship working correctly.

Here are my mapping files:

Parent Class Mapping

<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>

Child Class Mapping

<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 can somebody help.

A: 

For anyone else finding this, it appears the issue has been fixed in nhibernate 2.1, so you should just update.

KeeperOfTheSoul