1

I need to save a hibernate object into session and then retrieve one of it's foreign key properties like this:

public ActionResult Login(LoginModel model, string returnUrl) {
    User usr = _userRepository.GetById(Convert.ToInt32(ModelState["User"].Value.AttemptedValue));
    Session["user"] = usr;

}

public ActionResult Index() {
     Customer customerActive = Session["user"].Customer.Active;
     // this line throws an error:
    // Initializing[Myproj.Models.Customer#3]-Could not initialize proxy - no Session.
}

As User.Customer is a foreign key and NHIbernate lazy loads it, the call fails. How could I prevent this "No session" failure?

3
  • For example try this reading: hackingon.net/post/…. MVC and NHibernate means, introduce session per request. Open at the begining, close at the end. All the Lazy loaded features will have access to Session... there is nothing surprising... Commented Mar 6, 2014 at 7:44
  • This would not work as transactions are in this case only committed at the end of each request, meaning only a generic error page can be shown instead of specific ones. Commented Mar 6, 2014 at 8:07
  • Youd should use the full power of the MVC. Use one request for Write operations... another for display (success or error). This could be done easily with RedirectTo... both controller/action will have their own full session access Commented Mar 6, 2014 at 8:09

1 Answer 1

1

If you want to continue with existing approach you would want to make sure that Customer is initialized before it was put into the session, e.g.

var userId = Convert.ToInt32(ModelState["User"].Value.AttemptedValue);
User usr = _userRepository.GetById(userId);
NHibernateUtil.Initialize(usr.Customer);
Session["user"] = usr;

but...

as commentators have hinted there are probably various better approaches as the session is not a great place to store what might become large and complex objects which have to be serialized and stored remotely if you are in a web farm.

If passing the userId around and loading from the database each time is a performance hit for you there are several things you can do, e.g.

  • You could put some caching in front of the database call
  • Store some basic user data within a cookie (or local storage) to save any db hit -
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.