117

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?

Stefan
  • 919
  • 2
  • 13
  • 24
Arnold Zahrneinder
  • 4,788
  • 10
  • 40
  • 76
  • 9
    Imagine a situation where your db context would be disposed and lazy loading could not take place anymore. Then eager loading is beneficial. – Transcendent Jul 12 '15 at 09:36
  • 2
    I have seen a lot of projects fail because of performance problems due to the "N + 1 Select" problem which will occur faster when doing lazy loading, so be certain to look that up – David DV Jul 13 '15 at 09:15

9 Answers9

112

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.

farid bekran
  • 2,684
  • 2
  • 16
  • 29
  • 7
    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. – Ghasan غسان Jul 12 '15 at 09:52
  • 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 Jan 28 '20 at 12:48
43

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.

Indranil
  • 2,229
  • 2
  • 27
  • 40
  • 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. – rykamol Jun 19 '20 at 09:47
  • 1
    @rykamol Try to understand it as a design pattern. You can refer from here for better understanding: Eager Loading - https://www.entityframeworktutorial.net/eager-loading-in-entity-framework.aspx, Lazy Loading - https://www.entityframeworktutorial.net/lazyloading-in-entity-framework.aspx, Explicit Loading - https://www.entityframeworktutorial.net/EntityFramework4.3/explicit-loading-with-dbcontext.aspx – Indranil Jun 23 '20 at 04:49
  • 6
    @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. – Flater Feb 12 '21 at 15:31
  • @Flater Thank you so much. I'm not gonna forget that anymore. – rykamol Feb 14 '21 at 10:05
32

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.

serhiyb
  • 4,753
  • 2
  • 15
  • 24
  • 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 Jan 28 '20 at 12:49
16

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.

Transcendent
  • 5,598
  • 4
  • 24
  • 47
  • 3
    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). – Miroslav Holec Dec 05 '15 at 15:30
  • @MiroslavHolec: Brilliant, that's what I actually do using Ninject. What you just mentioned is indeed very very nice. – Transcendent Dec 06 '15 at 08:25
15

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.

Sheriff
  • 738
  • 10
  • 20
5

Lazy loading - is good when handling with pagination like on page load list of users appear which contains 10 users and as the user scrolls down the page an API call brings next 10 users. It's good when you don't want to load the entire data at once as it would take more time and would give a bad user experience.

Eager loading - is good as other people suggested when there are not many relations and fetch entire data at once in a single call to the database

-1

From an SEO perspective, lazy loading helps preserve resources until you load an image helping keep load time down, so is often used to increased website loading speeds.

However sometimes this causes a delay for Googles 'First Contentful Paint' (FCP) metric so it is recommended to use loading='eager' for banner images and 'above the fold' content. Particularly on the home page.

Jean
  • 9
  • 1
-3
// Using LINQ and just referencing p.Employer will lazy load
// I am not at a computer but I know I have lazy loaded in one
// query with a single query call like below.
List<Person> persons = new List<Person>();
using(MyDbContext dbContext = new MyDbContext())
{
    persons = (
        from p in dbcontext.Persons
        select new Person{
            Name = p.Name,
            Email = p.Email,
            Employer = p.Employer
        }).ToList();
}
  • 1
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) 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. – He Yifei 何一非 Jan 29 '17 at 03:53
  • 1
    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`" – Mischa Sep 12 '17 at 06:04
-3

It is better to use eager loading when it is possible, because it optimizes the performance of your application.

ex-:

Eager loading

var customers= _context.customers.Include(c=> c.membershipType).Tolist();

lazy loading

In model customer has to define

Public virtual string membershipType {get; set;}

So when querying lazy loading is much slower loading all the reference objects, but eager loading query and select only the object which are relevant.

  • 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 Dec 12 '18 at 18:07
  • #FakeCaleb has removed his comment – Nuwan Dhanushka Dec 13 '18 at 17:31
  • A mod removed my comment, I didn't see the point in continuing this conversation as you misunderstood my comment anyways from your response – FakeCaleb Dec 17 '18 at 08:28
  • 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. – Nuwan Dhanushka Dec 17 '18 at 16:17
  • 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. – FakeCaleb Dec 17 '18 at 16:44
  • [link](https://visualstudiomagazine.com/articles/2016/11/01/lazy-loading-in-entity-framework.aspx) I also try to mention like this kind of message in my comment, please refer. – Nuwan Dhanushka Dec 17 '18 at 17:02
  • 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... – FakeCaleb Dec 18 '18 at 08:32
  • 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..! – Nuwan Dhanushka Dec 19 '18 at 05:40
  • When you don't need the child objects........Literally the better answers in this explain when to use lazy and when to use eager... – FakeCaleb Dec 19 '18 at 10:41