nhibernatefluent-nhibernatestaleobjectstate

How should NHibernate update properties mapped as Version


Using fluent NHibernate I have a property on a class mapped using Version

Version(x => x.Version);

When I save the object, the Version property gets incremented in the database as I would expect, but the value of the property on the object only seems to change sometimes.

using (var tx = session.BeginTransaction())
{
    session.Merge(item);
    tx.Commit();

    item.Version;  // Sometimes this is still 1, when I expect it to be 2.
}

The problem is then that if it remains as 1 and I make more changes and save again I get a StaleObjectStateException.

What's weird is that sometimes it works fine and the item.Version value does get correctly incremented, but I can't figure out the difference between the cases where it does and the cases where it doesn't.

I've tried searching but can't seem to find any documentation on this. Can anyone explain what NHibernates expected behaviour is with the Version mapping?

[NHibernate version 2.1.2]


Solution

  • Did you try

    item = session.Merge(item);
    tx.Commit();
    

    ?