NHibernate When to Use lazy loading? [closed]

2019-07-13 12:01发布

问题:

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.

回答1:

I would put it this way:

Lazy loading is the essence of ORM. It is the principle of ORM. (unless we want to load complete DB in one shot)

Check this article by Ayende:

NHibernate is lazy, just live with it

small cite from that source:

...There is a good reason why lazy is set to true by default, and while I am sure that there is some limited number of scenarios where lazy=”false” is the appropriate choice, it isn’t for your scenario...

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:

  • Let the ORM stuff be lazy
  • adjust the ad hoc queries as needed


回答2:

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.