NHibernate.LazyInitializationException: failed to lazily initialize a collection, no session or session was closed

I have implemented a repository that essentially wraps up and centralises my calls to the NHibernate API. This facade is responsible for creating and disposing the NHibernate session.

Clients do not directly interact with the session.

So I use the IDetachedQuery interface to hold my queries like soz:

IDetachedQuery query = new DetachedQuery("...");

ITask task = repository.Find <Task>(query);

My task has a collection of categories which I am attempting to clear, but the session with which this collection is associated has already been disposed, so looks like I am going to have to force the collection to initialise before I return from the find method. The other option is to eagerly load the stuff i.e. set lazy loading to false.

As in Hibernate non-lazy loading is the default for loading collections in NHibernate. The solution to this problem was a case of setting the lazy attribute to false like this:

<set name="Categories" table="TaskCategory" lazy="false" cascade="all">

NHibernate can also be forced to initialize the collection by calling NHibernateUtil.Initialize(myObject) before the session is disposed.

No comments:

Purging Broadcom Drivers for Broadcom Wifi Card on Ubuntu sudo apt-get purge bcmwl-kernel-source   Reference: https://askubuntu.com/qu...