All I understand about lazy loading is that it loads only when the object is needed and we should use it. Please explain me which scenarios we have to use and not use it? Thanks in advance.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
To answer your question shortly: I would recommend you to use lazy loading, but you have to design your application with lazy loading in mind.
A more thorough answer: Lazy loading is the default in NHibernate. So if you are not doing anything to circumvent it, you are going to use lazy loading.
With lazy loading you can use nested objects (with many relationships to other tables) and it is going to work fine. They are loaded from the database as needed.
This can lead to some problems - the most famous is the n+1 problem. Ayende Rahien discussed this here: http://ayende.com/blog/3732/solving-the-select-n-1-problem
These problems can be circumvented if you declare which object should be eagerly fetched - or with some smarter queries - but you have to keep this in mind.
Another possible pitfall is that you can't lazy load an object if the session is already closed. This depends hugely on the kind of application you are programming and how you are using your objects. We had a rich client application with many nested objects and this took us some time to get the session handling right - but in the end it worked beautiful.
Ayende Rahien explains some of the reasons why NHibernate is using lazy loading in this post: http://ayende.com/blog/4573/nhibernate-is-lazy-just-live-with-it
Maybe this gives you some pointers to learn more about NHibernate and how to use lazy loading safely.
I would put it this way:
Check this article by Ayende:
NHibernate is lazy, just live with it
small cite from that source:
From my experience:
I would hardly explain it better than that post by Ayende. But I have to confirm - I see it the same way. I never used NON lazy setting. If something should be loaded in one shot - use projections: