NHibernate -failed to lazily initialize a collection of role

jamesaharvey picture jamesaharvey · Dec 12, 2009 · Viewed 22.2k times · Source

I have the following seemingly simple scenario, however I'm still pretty new to NHibernate.

When trying to load the following model for an Edit action on my Controller:

Controller's Edit Action:

public ActionResult Edit(Guid id)
{
    return View(_repository.GetById(id));
}

Repository:

public SomeModel GetById(Guid id)
{
    using (ISession session = NHibernateSessionManager.Instance.GetSession())
        return session.Get<SomeModel >(id);
}

Model:

public class SomeModel
{
    public virtual string Content { get; set; }
    public virtual IList<SomeOtherModel> SomeOtherModel { get; set; }
}

I get the following error:

-failed to lazily initialize a collection of role: SomeOtherModel, no session or session was closed

What am I missing here?

Answer

Stefan Steinegger picture Stefan Steinegger · Dec 12, 2009

The problem is that you create and also close the session in you models GetById method. (the using statement closes the session) The session must be available during the whole business transaction.

There are several ways to achieve this. You can configure NHibernate to use the session factories GetCurrentSession method. See this on nhibernate.info or this post on Code Project.

public SomeModel GetById(Guid id)
{
    // no using keyword here, take the session from the manager which
    // manages it as configured
    ISession session = NHibernateSessionManager.Instance.GetSession();
    return session.Get<SomeModel >(id);
}

I don't use this. I wrote my own transaction service which allows the following:

using (TransactionService.CreateTransactionScope())
{
  // same session is used by any repository
  var entity = xyRepository.Get(id);

  // session still there and allows lazy loading
  entity.Roles.Add(new Role());

  // all changes made in memory a flushed to the db
  TransactionService.Commit();
}

However you implement it, sessions and transactions should live as long as a business transaction (or system function). Unless you can't rely on transaction isolation nor rollback the whole thing.