Reputation: 1500
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
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.
Upvotes: 1