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?
I think it is good to categorize relations like this
When to use eager loading
When to use lazy loading
Note: like Transcendent said there may be disposal problem with lazy loading.
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:
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:
NOTE: Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.
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.