NHibernate Lazy Download - After Closing Session

Is it possible to lazy load a linked object during an open session, but still have a linked object available after the session is closed?

For example, we have the class USER and the class ROLE associated with it. When we load the USER, we are also lazy to load the associated ROLE object. Can we have the USER and ROLE class fully loaded and accessible after the session is closed?

Is it possible to use this function?

+4
source share
3 answers

The short answer is no. You must initialize everything you need after closing the session, before closing the session. The method used to force the download of a lazy proxy (without listing), NHibernateUtil.Initialize(USER.ROLES) .

Long answer ... kind of. You can "re-bind" objects to a new session, thereby allowing you to initialize PersistentBags and other NH proxies. The best way to use it, given that you know that the object exists in the database but not in your new session, and that you have not changed it yet, is Session.Lock(USER, LockMode.None) . This will associate the object with a new session without telling NHibernate to do anything regarding reading or writing to the object.

HOWEVER, keep in mind that this is the smell of code. If you regularly connect objects to new sessions, this is a sign that you are not having enough sessions. For example, there is no problem opening one session for one window shape and opening it as long as the form is open, REPRESENTS that you close it when the window closes.

+8
source

If you are dealing with a ratio of 1-1 (0-1 roles per user), then perhaps the simplest option would be to configure it to get the desired result, and not for lazy loading. Lazy loading is really focused on 1- * relatives or objects that are especially large and rarely needed. NH does a pretty good job of optimizing queries to include fast data fast in such scenarios.

0
source

Yes. When the session is closed, all objects that have been lazily loaded will remain in memory and you can access them without any problems.

0
source

Source: https://habr.com/ru/post/1332986/


All Articles