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!
You need to use the Session per Request pattern. See this link for an explanation of the best practices for using NHibernate with ASPX.