Why is NHibernate lazy loading associated with a session?

Using Castle ActiveRecord, I ran into a problem with lazy loading.

The following works (obviously)

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

Since I need to change session filters in a specific context (using interceptors), I create 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 of “singleUser.Groups” throws a LazyInitializationException: “failed to lazily initialize the role collection: groups, session or session closed”.

However, all other session operations work correctly. Thus, it seems that "singleUser" is tied to an already installed SessionScope. What for? And how can this be solved alternatively?

+4
source share
2 answers

My GUESS - part of the reason is for the Identity Card. Not only lazy downloadable objects, but all objects are attached to the session. This ensures that two objects do not represent the same row in the database.

0
source

I believe this works for NHibernate.

All your entities are session-bound and use this for lazy loading. If you host a session, you won’t be able to get lazy loaded collections and properties. The answer, obvious given this limitation, is to avoid deleting the session — or keep the session until you retrieve the data you need.

The internal volume does not differ from the external; it does not support lazy loading outside this area.

However, you can get around this limitation if you trick NHibernate into eager loading in your internal area. Alternatively, call .ToList() or the like in the collections you would like to work with before leaving the scope, and the data will also be accessible from the outside.

+4
source

All Articles