Question

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 :)

Was it helpful?

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.

OTHER TIPS

You can't, and you shouldn't.

If a transaction fails, you must abort the request and show an error.

The logical corollary is that session exceptions should not be part of your regular flow.

Now, since you're using MVC, here's an example of how error handling might work if you allow errors:

public ActionResult CreateFoo(FooModel model)
{
    if (ModelState.IsValid)
    {
        try
        {
            SaveThe(model);
            TheTransaction.Commit();
            return RedirectToAction("Whatever");
        }
        catch (WhateverTheDuplicateKeyExceptionIs)
        {
            ModelState.AddModelError("", "Duplicate XYZ");
        }
    }
    return View();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top