I have an entity mapped in NHibernate with optimistic concurrency control using a SQL timestamp column as the version number. The mapping is like the following:
<class name="Entity" optimistic-lock="version" discriminator-value="0">
<id name="id">
<generator class="native" />
</id>
<version name="Version" column="Version" generated="always" unsaved-value="null" type="System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
...
<subclass name="ChildEntity" discriminator-value="1" />
</class>
I am testing what happens when the data in a row in the database changes between the get and the update of the record. To do so, I am running an update statement directly against one of the records in the table that are in the process of being updated by NHibernate. This direct update changes the version number of the record in the table.
As expected, the NHibernate managed update does not occur on the specific row (this is good). However, no exception is thrown during the commit. I expected a StaleObjectStateException to occur when the transaction was committed so that I could roll back the transaction and inform the user. Isn't this the expected behavior? Am I missing something?
My code to commit the transaction looks something like this:
_session.BeginTransaction();
...
// load objects in session
IList<ChildEntity> toChange = _session.Find('some condition');
foreach ( var itemToChange in toChange )
{
itemToChange.Status = Status.Updated;
}
...
_session.Transaction.Commit();
The items belong to the same session and all work is completed within a single transaction. ChildEntity is a subclass of the Entity base class, which has the optimistic-lock set to version.