Native SQL Queries in NHibernate transaction

1.5k Views Asked by At

Short and sweet:

  1. Should I always flush a SessionScope before making any native SQL query in my application?

    I guess the answer is 'yes' because NHibernate implements caching, so maybe changes made are still not in the DB so the query would get inconsistent results.

  2. How is the correct way to make those queries in the same transaction of the current active one in NHibernate?

    This is important because I could get deadlocks in my business logic.

Further documentation about both questions would be appreciated too!

1

There are 1 best solutions below

0
On

(I assumed that by "flushing" you're mentioning ISession.Flush()):

  1. The quick answer is: It depends on your flush mode, if it's Never you will have to flush the session yourselves, but if it's Auto, NHibernate will flush before issuing the query.
  2. There are two ways to execute native SQL queries with NHibernate. One is to use NHibernate's own native SQL support like using named query or ISession.CreateSQLQuery(). Other is to use NHibernate ITransaction.Enlist(). However, I'm not sure if executing a DbCommand using Enlist() will flush the session.