Вопрос

I have a scenario similar to this: Asp.NET MVC 4 website using nHibernate Session Per Request. The session is injected using Ninject onto a Repository with the Get and Save methods.

There are a lot of articles talking about Session Per Request and saying that is the way to do things on a web application.

But i'm having problems implementing logic like this one:

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 view with a message to the user. But i have also to refresh the resulting web page, so i have also to read some information from the database.

According to nHibernate documentation, the session with the exception must be discarded Documentation Here

But i can't find any articles about the best way to proceed here.

What's the best approach for this situation?. I will have to inject a new Session to my repository object?.

Thanks.

Это было полезно?

Решение

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

I do this in some of my Actions where I expect unique key violations to occur and I have to reload lookup data in the model. Here's 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);
    }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top