119

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?

2
  • 11
    Imagine a situation where your db context would be disposed and lazy loading could not take place anymore. Then eager loading is beneficial. Commented Jul 12, 2015 at 9: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 Commented Jul 13, 2015 at 9:15

10 Answers 10

116

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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 ?
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.

4 Comments

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 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/…
@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 Thank you so much. I'm not gonna forget that anymore.
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.

1 Comment

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 ?
17

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.

2 Comments

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).
@MiroslavHolec: Brilliant, that's what I actually do using Ninject. What you just mentioned is indeed very very nice.
17

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.

Comments

6

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

4 Comments

Continous scroll or paging != lazy loading.
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.
It's not lazy loading in the clear and specific context of Entity Framework.
Pagination is other thing
0

1. Eager Loading

Eager loading retrieves related data in advance as part of the initial query. This reduces the number of queries executed, especially when iterating over related models.

If you have an Image model related to other models (e.g., Post, User), eager loading can ensure all images related to the queried models are fetched in a single query.

Laravel Example code :

class Post extends Model
{
    public function images()
    {
        return $this->hasMany(Image::class);
    }
}

// Query with Eager Loading
$posts = Post::with('images')->get();

foreach ($posts as $post) {
    foreach ($post->images as $image) {
        echo $image->url;
    }
}

2. Lazy Loading

The Lazy loading retrieves related data only when accessed. Each access to a relationship executes a separate query.

When you are uncertain whether related images will be accessed, lazy loading fetches them only when required.

Laravel Example Code :

$posts = Post::all(); // Fetch posts without images

foreach ($posts as $post) {

    // Query executed here
    foreach ($post->images as $image) { 
        echo $image->url;
    }
}

When to Use Eager Loading & Lazy Loading ?

  1. Eager Loading: 1.1. Use when you know you'll need the related images upfront. 1.2. Reduces the number of queries (prevents N+1 problem). 1.3. Example: Fetching posts with all their images for a gallery.

  2. Lazy Loading:

    2.1 Use when the related images might not always be needed. 2.2 Can result in unnecessary queries if multiple related records are accessed.

Comments

-2

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.

Comments

-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();
}

2 Comments

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.
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"
-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.

9 Comments

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.
#FakeCaleb has removed his comment
A mod removed my comment, I didn't see the point in continuing this conversation as you misunderstood my comment anyways from your response
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.
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.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.