Lazy Loading vs Eager Loading

132,529

Solution 1

I think it is good to categorize relations like this

When to use eager loading

  1. In "one side" of one-to-many relations that you sure are used every where with main entity. like User property of an Article. Category property of a Product.
  2. Generally When relations are not too much and eager loading will be good practice to reduce further queries on server.

When to use lazy loading

  1. Almost on every "collection side" of one-to-many relations. like Articles of User or Products of a Category
  2. You exactly know that you will not need a property instantly.

Note: like Transcendent said there may be disposal problem with lazy loading.

Solution 2

Eager Loading: Eager Loading helps you to load all your needed entities at once. i.e. related objects (child objects) are loaded automatically with its parent object.

When to use:

  1. Use Eager Loading when the relations are not too much. Thus, Eager Loading is a good practice to reduce further queries on the Server.
  2. Use Eager Loading when you are sure that you will be using related entities with the main entity everywhere.

Lazy Loading: In case of lazy loading, related objects (child objects) are not loaded automatically with its parent object until they are requested. By default LINQ supports lazy loading.

When to use:

  1. Use Lazy Loading when you are using one-to-many collections.
  2. Use Lazy Loading when you are sure that you are not using related entities instantly.

NOTE: Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.

Solution 3

Lazy loading will produce several SQL calls while Eager loading may load data with one "more heavy" call (with joins/subqueries).

For example, If there is a high ping between your web and sql servers you would go with Eager loading instead of loading related items 1-by-1 with lazy Loading.

Solution 4

Consider the below situation

public class Person{
    public String Name{get; set;}
    public String Email {get; set;}
    public virtual Employer employer {get; set;}
}

public List<EF.Person> GetPerson(){
    using(EF.DbEntities db = new EF.DbEntities()){
       return db.Person.ToList();
    }
}

Now after this method is called, you cannot lazy load the Employer entity anymore. Why? because the db object is disposed. So you have to do Person.Include(x=> x.employer) to force that to be loaded.

Solution 5

Eager Loading When you are sure that want to get multiple entities at a time, for example you have to show user, and user details at the same page, then you should go with eager loading. Eager loading makes single hit on database and load the related entities.

Lazy loading When you have to show users only at the page, and by clicking on users you need to show user details then you need to go with lazy loading. Lazy loading make multiple hits, to get load the related entities when you bind/iterate related entities.

Share:
132,529
Arnold Zahrneinder
Author by

Arnold Zahrneinder

Zei tchewandergehte miezch schtutenawkenen vech ichtanspolzovalt. Technologunden verhnachthayete miezch schtwergte Java siender C#, funderhagte meizch utherwarzin lungunstenen tcherstwastender. Zurch tiech faldangenen enst debei machzen

Updated on September 08, 2021

Comments

  • Arnold Zahrneinder
    Arnold Zahrneinder over 2 years

    Under what situation could eager loading be more beneficial than lazy loading?

    Lazy loading in Entity Framework is the default phenomenon that happens for loading and accessing the related entities. However, eager loading is referred to the practice of force-loading all these relations.

    I'm asking this, because it is obvious that lazy loading is more resource-friendly, and even if we use the ToList() method, we can still take advantage of the lazy loading behavior.

    However, I thought maybe lazy loading increases the number of requests to the actual database and maybe that's why sometimes developers use the Inlcude method to force-loading all relations.

    For example, when using the Visual Studio auto-scaffolding in MVC 5, the Index method automatically created in the controller always uses Eager Loading, and I've always had the question of why Microsoft uses Eager Loading default in that case.

    I would appreciate it if someone explains to me under what situation eager loading would be more beneficial than lazy loading, and why do we use it at all while there's something more resource-friendly as Lazy Loading?

  • Ghasan غسان
    Ghasan غسان almost 9 years
    I wast just trying to answer the same thing. Use lazy loading when you know you will rarely need to use the related data. But when you know you will want certain related data quite often, use eager loading.
  • Miroslav Holec
    Miroslav Holec over 8 years
    Yes, that is example when Lazy Loading does not help. Another thing is that creating DbContext everytime you will need some data is bad way. If you some IoC container, your DbContext will live along with Request (in case of web apps).
  • Transcendent
    Transcendent over 8 years
    @MiroslavHolec: Brilliant, that's what I actually do using Ninject. What you just mentioned is indeed very very nice.
  • He Yifei 何一非
    He Yifei 何一非 about 7 years
    While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
  • Mischa
    Mischa over 6 years
    This answer does not address OPs question at all. OP is not asking about how to do Lazy loading, he is asking about "when to use Lazy loading and when Eager Loading"
  • Nuwan Dhanushka
    Nuwan Dhanushka over 5 years
    use performance diagnostics tools like Glimpse and check how both works while lazy loading having multiple connections and queries eager only have only one. I have check those practically, please mention why you saying that wrong.
  • Nuwan Dhanushka
    Nuwan Dhanushka over 5 years
    #FakeCaleb has removed his comment
  • FakeCaleb
    FakeCaleb over 5 years
    A mod removed my comment, I didn't see the point in continuing this conversation as you misunderstood my comment anyways from your response
  • Nuwan Dhanushka
    Nuwan Dhanushka over 5 years
    You didn't mention the exact point and said that my comment is completely misleading, if you mention what are the points which are incorrect i also can learn.
  • FakeCaleb
    FakeCaleb over 5 years
    I just think due to wording you connote that eager loading is better than lazy loading due to performance. I can think of scenarios where this is not true.
  • Nuwan Dhanushka
    Nuwan Dhanushka over 5 years
    link I also try to mention like this kind of message in my comment, please refer.
  • FakeCaleb
    FakeCaleb over 5 years
    Have you actually read this what you have linked? He's talking about when retrieving child objects, which is a good use case for eager loading. You're using one use case and applying to all use cases...
  • Nuwan Dhanushka
    Nuwan Dhanushka over 5 years
    Clearly I red that's why i attached it to magnify my answer, have you got any simple scenario which is imply lazy loading is more optimized in performance then it is easy to understand like any link i have attached..!
  • FakeCaleb
    FakeCaleb over 5 years
    When you don't need the child objects........Literally the better answers in this explain when to use lazy and when to use eager...
  • Ahmad Alaa
    Ahmad Alaa about 4 years
    can i use both together ?, for example if entity is almost related to another i can include it via eager loading, and other related entities will be via lazy loading ?
  • Ahmad Alaa
    Ahmad Alaa about 4 years
    can i use both together ?, for example if entity is almost related to another i can include it via eager loading, and other related entities will be via lazy loading ?
  • rykamol
    rykamol almost 4 years
    I'm really confused about eager and lazy loading. could you make me understand, please!By reference of google i fould this thing about lazy loading. "You should use virtual keyword, when you want to load data with lazy loading. lazy loading is the process whereby an entity or collection of entities is automatically loaded from the database the first time it is accessed.Jan 7, 2016 " is that the same thing that you said about lazy loading.
  • Dark Matter
    Dark Matter almost 4 years
    @rykamol Try to understand it as a design pattern. You can refer from here for better understanding: Eager Loading - entityframeworktutorial.net/…, Lazy Loading - entityframeworktutorial.net/…, Explicit Loading - entityframeworktutorial.net/EntityFramework4.3/…
  • Flater
    Flater about 3 years
    @rykamol: If I ask you to get me Tom's personal data and I alert you that I will probably need personal data of (some of) his children; would you rather fetch all this data of Tom and all of his children at once (eager loading) or would you rather give me Tom's data and then promise me that you will go and get any of his children's data if I end up asking for it (lazy loading)? Both approaches have their benefit, lazy loading can avoid loading unused data, but eager loading minimizes the trips to the database.
  • rykamol
    rykamol about 3 years
    @Flater Thank you so much. I'm not gonna forget that anymore.
  • Gert Arnold
    Gert Arnold almost 3 years
    Continous scroll or paging != lazy loading.
  • Iqra Abdul Rauf
    Iqra Abdul Rauf almost 3 years
    Yea sir, it is just an example for clarity, lazy loading is basically loading/fetching the data until the point at which it is needed.
  • Gert Arnold
    Gert Arnold almost 3 years
    It's not lazy loading in the clear and specific context of Entity Framework.