Rok
Rok

Reputation: 1500

ASP MVC4 + NHibernate objects in Session

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?

Upvotes: 1

Views: 164

Answers (1)

dove
dove

Reputation: 20674

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 -

Upvotes: 1

Related Questions