NHibernate Transactions
For my ASP.NET project I'm using the nice NHibernate template from Billy McCafferty. Work's exactly the way I want. But I noticed one thing which isn't that good after all. A transaction rollback does not work. One ends up with all the changes persisted to the database. The problem was, that the NHibernate example uses a session.flush() even after a rollback - which is not the recommended by the NHibernate documentation. The comments on the CodeProject page were quite helpful, as well as a discussion at stackoverflow. The solutiion for this problem: Just don't flush after rollback.
public void RollbackTransaction() {
ITransaction transaction = ContextTransaction;
try {
if (HasOpenTransaction()) {
transaction.Rollback();
}
ContextTransaction = null;
}
finally {
CloseSession(false);
}
}
public void CloseSession(bool flush)
{
ISession session = ContextSession;
if (session != null && session.IsOpen)
{
if(flush)
session.Flush();
session.Close();
}
ContextSession = null;
}