tags:

views:

64

answers:

2

I am using NHibernate for my project. i am quite a beginner at working on NHibernate.

I use many-to-many relation mapping "users" and "roles". Here is the code to get the user:

public User GetUser(int userId){
  using(ISessuib session = new SessionManager().GetSession())
  {
     return session.Get<User>(userId);
  }
}

public void LazyLoadUsingSessionTest(){
  var user= GetUser(1);
  Assert.NotNull(user.Roels);
}

it throws an exception:failed to lazily initialize a collection, no session or session was closed

if i do not use the "using" statement in the "GetUser" method,it works. But i must call the session.Close() to release the resource

when i use it in a web page,i only want to use the GetUser(), not the ISession object.so my question is : Does it mean that i must have a ISession object(to release resouse) in my web page? or any better solution?(because i do not want the ISession object appears in my aspx.cs files)

thanks!

+2  A: 

You need to use the Session per Request pattern. See this link for an explanation of the best practices for using NHibernate with ASPX.

Richard Bramley
A: 

The simplest way is to use NHibernateUtil.Initialize (read here for details):

using(ISession session = new SessionManager().GetSession())
{
  User user = session.Get<User>(userId);
  NHibernateUtil.Initialize(user.Roles);
  return user;
}

However, sooner or later you would need to somehow manage the sessions in your application. I recommend creating a data provider layer that would give you access to the database. The data provider layer will manage the creation and destruction of sessions. You could either have a session per request or per conversation (single ISession for the duration of an ASP.Net session).

The Summer Of NHibernate video series would be helpful. Session 5 and 13 are most relevant for you.

kgiannakakis
Sorry, but this is a bad advise. This way you destroy lazy loading and transaction isolation at the same time, while blowing up the code with lots of rubbish.
Stefan Steinegger