Search code examples
entity-frameworklinqeager-loading

Why use .ToList after .Include in Eager Loading


This might be easy, but I was wondering why whenever using the process of eagerly loading that .ToList() has to be used after .Include()?

I know that eagerly loading allows for the loading of related entities along with the main entity for query purposes, but why does .ToList() have to be used?

Is it for a memory purpose or something?

For example:

using (var context = new BloggingContext()) 
{ 
    // Load all blogs and related posts 
    var blogs1 = context.Blogs 
                      .Include(b => b.Posts) 
                      .ToList(); // why is this needed?
}

Any explanation/help is greatly appreciated.


Solution

  • It is during the ToList() call when the query will actually be immediately executed. So, your previous Include will setup the projection before hitting the database