Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate Lazy Loading - After the session closes

Is it possible to lazy load a related object during an open session but to still have the related object available after the session closes?

For example, we have a USER class and a related ROLE class. When we load a USER we also lazy load the related ROLE object. Can we have the USER and ROLE class fully loaded and available after the session is closed?

Is this functionality possible?

like image 897
Piere Avatar asked Feb 25 '23 13:02

Piere


1 Answers

Short answer: no. You must initialize anything you will need after the session closes, before closing the session. The method to use to force loading a lazy proxy (without enumerating it) is NHibernateUtil.Initialize(USER.ROLES).

Long answer... kind of. It is possible to "reattach" objects to a new session, thereby allowing PersistentBags and other NH proxies to be initialized. The best method to use, given that you know the object exists in the DB but not in your new session, and that you haven't yet modified it, is Session.Lock(USER, LockMode.None). This will associate the object with the new session without telling NHibernate to do anything regarding reads or writes of the object.

HOWEVER, be advised that this is a code smell. If you are regularly reattaching objects to new sessions, it is a sign that you are not keeping sessions open long enough. There is no problem with opening one session per windows form, for instance, and keeping it open as long as the form is open, PROVIDED you close it when the window closes.

like image 149
KeithS Avatar answered Mar 05 '23 16:03

KeithS