开发者

NHibernate many to many and ISession.Close()

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜