NHibernate session for each request and exception management

I have a scenario similar to this: Asp.NET MVC 4 website using nHibernate session for request. A session is introduced using Ninject into the repository using the Get and Save methods.

There are many articles that talk about the session behind the request and say that this is a way to do something in a web application.

But I have problems with implementing this logic:

Read Data From Database Alter Entity information Save to Database Read another entity Alter entity Save ... but an EXCEPTION OCCURS 

I want to show my opinion with a message to the user. But I am also updating the resulting webpage, so I also have to read some information from the database.

According to nHibernate documentation, session with exception should be dropped Documentation here

But I cannot find articles on how best to move on.

What is the best approach for this situation ?. Will I need to add a new session to my repository object?

Thanks.

+4
source share
1 answer

You can create a new session from the SessionFactory property of the original session. You can access the original session object either by exposing it in the repository class, or by typing it into the controller. Then you can create a new repository with a new session.

I do this in some of my actions, where I expect that unique key violations will be detected, and I will have to reload the search data in the model. Here is an example:

  public ActionResult Create(MeasuresEditView model) { if (ModelState.IsValid) { using (var txn = _session.BeginTransaction()) { try { var measure = new Measure { Code = model.Code }; _session.Save(measure); txn.Commit(); return RedirectToAction("Index"); } catch (UniqueKeyException) { txn.Rollback(); var msg = string.Format("A measure with the code '{0}' already exists, please enter a different code or cancel.", model.Code); ModelState.AddModelError("Code", msg); } catch (Exception ex) { if (txn.IsActive) { txn.Rollback(); } log.Error("Create", ex); throw; } } } // have to rebuild selectlist on post in new txn in case it was rolled back using (var session = _session.SessionFactory.OpenSession()) using (var txn = session.BeginTransaction()) { SetProductGroupSelectList(session, model, manualId); txn.Commit(); } return View(model); } 
+4
source

All Articles