Why do you start a transaction if you only read during that transaction ?
That is completely not-necessary.
Although, it is true that, if you've set the connection-release mode to 'after_transaction', the connection will only be closed once the transaction has been committed or rollbacked. So in these cases, it can indeed by handy to start a transaction if you want to perform multiple read-actions.
In fact, what I mostly do, is this:
Person p = null;
using( ISession s = sf.OpenSession())
{
With.Transaction (s, () => p = s.Get (1));
}
for instance.
Where 'With.Transaction
' is a utility method which starts a transaction, executes the passed delegate (action), and then commit or roll backs the transaction.
It looks very much like this:
public static class With
{
public static void Transaction( ISession s, Action proc )
{
using( ITransaction thx = s.BeginTransaction () )
{
try
{
proc();
thx.Commit();
}
catch
{
thx.Rollback();
throw;
}
}
}
}
But, my implementation is still slightly different, since I do not use the NHibernate's ISession
directly.
Instead, I've created a wrapper around the ISession
, and in that wrapper I also keep track of the current Transaction (if there is one) for that session.
By doing so, in the With.Transaction
method, I can check whether my session already has an active transaction or not, and then, I only start a transaction if there is no transaction already active.
(Credits go to Ayende for the With.Transaction
idea).