Thursday, July 16, 2009

Don't flush the Session after an exception occurs

I recently moved my all 'flush' at central location i.e. on session closed. And I close session in "finally" block of the code, to ensure that it really gets closed (not really).
So code would look like

//Use Session like never used before
//closes session that was assigned to the thread

CloseCurrentSession in NhibernateSessionManager would look like this,

ISession session = GetCurrentContextSession();
if(session != null && session.IsOpen)
session.Flush(); //evil is here

I was proud of this solution until I got into a database exception in my main code (which happens rarely after I write millions of lines of code).
If any such exception occurred and you try to flush, you will be delighted with another exception when you use session.Flush() It says "don't flush the Session after an exception occurs". For undisclosed reason, I couldn't use autoflush (reserved for next blog may be ;)

I believe there are alternate solutions but I as I told, I am lazy (like any other ORM), so I reverted back to my 'Flush manually' everytime when you make some entity dirty. Pretty shitty stuff huh???

Anyways, thanks for reading the blog even though the title "Don't flush the Session after an exception occurs" tells it all and inside matter is just ramblings.

No comments: