Today I came accross a question whether we need to commit the transactions we use for reading data. I found a good explanation at http://www.hibernatingrhinos.com/products/nhprof/learn/alert/donotuseimplicittransactions for NHibernate context.
Quoting the article “
A common mistake when using a database is to use transactions only when orchestrating several write statements. In reality, every operation that the database is doing is done inside a transaction, including queries and writes (update, insert, delete).
Note: In SQL Server, ‘Implicit Transactions’ are usually called ‘Autocommit Transactions’.
When we don’t define our own transactions, it falls back into implicit transaction mode, where every statement to the database runs in its own transaction, resulting in a large performance cost (database time to build and tear down transactions), and reduced consistency.
Even if we are only reading data, we should use a transaction, because using transactions ensures that we get consistent results from the database. NHibernate assumes that all access to the database is done under a transaction, and strongly discourages any use of the session without a transaction.”
Example of valid code:
using(var session = sessionFactory.OpenSession())
using(var tx = session.BeginTransaction())
// execute code that uses the session