Thursday 8 March 2007

NHibernate Flush before Query

Was having a problem with following:
  1. Start Session
  2. Read object/record (presentation layer)
  3. Update record/object im memory (presentation layer)
  4. Run query to check changes valid (biz layer).
  5. If 4 ok commit changes inside transaction (biz layer)
  6. End session
Step 4 was identifying a problem and so steps 5 was not completed (i.e. no explicit Commit was called), the problem was that the record changes were still being written to the database.

This is caused by the FlushMode of the session be set to Auto. When set to auto NHibernate will sometimes flush the persistent obejct prior to performing a query.

There are a few solutions to this:
  • Perform updates to object after query (not applicable in this case due to layers)
  • Disconnect object prior to updating (Evict)
  • Change FlushMode to Commit
The solution decided upon was to change FlushMode to Commit and to also clear the session if a transaction fails and rollback is called.