Why is NHIBERNATE delayed loading binding to session?

Using Castle ActiveRecord, I stumbled upon a problem during lazy loading.

The following works (obviously)

using (new SessionScope())
{
User singleUser = User.FindFirst(...)
UserGroup groups = singleUser.Groups; // Lazy-loading groups.
}

Because I need to modify the session filter in a certain context (using an interceptor), I created a new SessionScope.

using (new SessionScope())
{
User singleUser;
EnableVariousFiltersInThisThread();
using (new SessionScope())
{
singleUser = User.FindFirst(...);
}
DisableVariousFiltersInThisThread();
UserGroup groups = singleUser.Groups; // Lazy-loading groups.
}

The last line “singleUser.Groups” throws a LazyInitializationException: “Cannot initialize the role set lazily: group, no session or session is closed”.

However, all other session operations are working properly . So it seems that “singleUser” is bound to the SessionScope being processed now. Why? How can we solve this problem?

My GUESS is – part of the reason is about the “identity map”. Not only does the object lazily load, but All objects are bound to the session. This ensures that no two objects represent a single row in the database.

Using Castle ActiveRecord, I stumbled upon a problem while lazy loading.

The following works (obviously)

using (new SessionScope())
{
User singleUser = User.FindFirst( ...)
UserGroup groups = singleUser.Groups; // Lazy-loading groups.
}

Because I need to modify the session filter in a certain context (using interceptor ), so I created a new SessionScope.

using (new SessionScope())
{
User singleUser;
EnableVariousFiltersInThisThread( );
using (new SessionScope())
{
singleUser = User.FindFirst(...);
}
DisableVariousFiltersInThisThread();
UserGroup groups = singleUser.Groups; // Lazy-loading groups.
}

The last line “singleUser.Groups” throws a LazyInitializationException: “Cannot initialize role collection lazily: group, no session Or the session is closed”.

However, all other session operations are working properly. So it seems that “singleUser” is bound to the SessionScope being processed now. Why? How can we solve this problem?

My GUESS is – partly because of the “identity map”. Not only are objects lazily loaded, but all objects are bound to the session. This ensures that there are no Two objects represent a single row in the database.

Leave a Comment

Your email address will not be published.