asp.net-mvcnhibernateisession

NHibernate ISession: Nothing can be persisted after an Exception


I have a problem with NHibernate ISession. When I try to persist something wrong into Database (e.g saving an entity with duplicate key on XYZ col) and rolling back Transaction; ISession instance goes to a BROKEN/INVALID state which doesn't persist any record after that, and each time NHibernat throws another exception that tells me about first time issue.

I've used ISession methods like Flush, Clear, Close but my problem exists. Another approach is to request another ISession instance from ISessionFactory but when I use this, another strange problem: illegal attempt to associate a collection with two open sessions.

How to recover an ISession instance without re-requesting another from ISessionFactory?

Thanks in advance :)


Solution

  • You cannot recover the ISession. From documentation:

    If the ISession throws an exception you should immediately rollback the transaction, call ISession.Close() and discard the ISession instance. Certain methods of ISession will not leave the session in a consistent state.

    Also creating ISession is cheap so there is no reason to try to reuse it. You probably want to have ISession per request if you have MVC application.