Eager Loading in Entity Framework

Eager Loading in Entity Framework

In this article, I am going to discuss Eager Loading in Entity Framework with Examples. Please read our previous article where we discussed LINQ to Entities Queries in Entity Framework. At the end of this article, you will learn how to load the entities eagerly. You will also learn how to Eager Loading from multiple Levels and multiple Tables with Examples.

In Entity Framework, we can load the related entities in three ways. They are Eager Loading, Lazy Loading, and Explicit Loading. All these three terms i.e. Eager Loading, Lazy Loading, and Explicit Loading are referring to the process of loading the related entities. That is, they define when to load the related entities or child entities. 

Note: We are going to work with the same example that we created in our Introduction to Entity Framework Database First articlePlease read our introduction to Entity Framework Database First article before proceeding to this article.

Eager Loading in Entity Framework

Eager loading is a Process where Entity Framework loads the related entities along with the main entity, so we don’t require to execute separate queries for related entities. That is all the entities are loaded in a single query to the database and hence saving bandwidth and crucial server CPU time.

In Entity Framework, the Eager Loading is done using the Include method. The Include method also has two overloads. One of which takes navigation property as a string. The Other Include method is an extension method and far more flexible.

Example:

When querying students, eager-load their Standards. The students and their Standards will be retrieved in a single query.

Eager Loading using LINQ Query Syntax:

In the following example, we use LINQ Query Syntax to fetch all the students from the database along with its standards using the Include() method.

using System;
using System.Linq;
namespace DBFirstApproach
{
    class Program
    {
        static void Main(string[] args)
        {
            using (EF_Demo_DBEntities context = new EF_Demo_DBEntities())
            {
                var students = (from s in context.Students.Include("Standard")
                             select s).ToList();

                foreach (var student in students)
                {
                    Console.WriteLine($"Firstname: {student.FirstName}, Lastname: {student.LastName}, StandardName: {student.Standard.StandardName}, Description: {student.Standard.Description}");
                }

                Console.Read();
            }
        }
    }
}

Eager Loading using LINQ Method Syntax:

In the below example, we use LINQ Method Syntax to fetch all the students from the database along with its standards using the Include() method.

using System;
using System.Linq;
namespace DBFirstApproach
{
    class Program
    {
        static void Main(string[] args)
        {
            using (EF_Demo_DBEntities context = new EF_Demo_DBEntities())
            {
                var students = context.Students
                   .Include("Standard").ToList();

                foreach (var student in students)
                {
                    Console.WriteLine($"Firstname: {student.FirstName}, Lastname: {student.LastName}, StandardName: {student.Standard.StandardName}, Description: {student.Standard.Description}");
                }

                Console.Read();
            }
        }
    }
}

As we use the Include method in the above two examples, in a single database query it will load the students along with the Standard data. So, when you execute the above two examples, the following SQL Script is generated and executed in the database and we captured this script using the SQL Profiler tool.

Eager Loading in Entity Framework

Eager Loading using Lambda Expression in Entity Framework:

You can also use the LINQ lambda expression as a parameter in the Include method. For this, you need to add a reference to System.Data.Entity namespace and use the lambda expression as shown in the below example.

using System;
using System.Linq;
using System.Data.Entity;
namespace DBFirstApproach
{
    class Program
    {
        static void Main(string[] args)
        {
            using (EF_Demo_DBEntities context = new EF_Demo_DBEntities())
            {
                var students = context.Students
                   .Include(x => x.Standard).ToList();

                foreach (var student in students)
                {
                    Console.WriteLine($"Firstname: {student.FirstName}, Lastname: {student.LastName}, StandardName: {student.Standard.StandardName}, Description: {student.Standard.Description}");
                }

                Console.Read();
            }
        }
    }
}
Load Multiple Entities using Include Method:

You can also eagerly load multiple levels of related entities using the Include method in Entity Framework. In the below example we eagerly load the Student, Standard, and Teacher entities.

using System;
using System.Linq;
using System.Data.Entity;
namespace DBFirstApproach
{
    class Program
    {
        static void Main(string[] args)
        {
            using (EF_Demo_DBEntities context = new EF_Demo_DBEntities())
            {
                var studentsMS = context.Students
                               .Include("Standard.Teachers").ToList();

                //Using Lambda Expression
                var studentsQS = context.Students
                               .Include(s => s.Standard.Teachers).ToList();
                
                foreach (var student in studentsMS)
                {
                    Console.WriteLine($"Firstname: {student.FirstName}, Lastname: {student.LastName}, StandardName: {student.Standard.StandardName}, Description: {student.Standard.Description}");
                }

                Console.Read();
            }
        }
    }
}

When you execute the above code, it will generate the following SQL Script and execute in the database.

SELECT 
    [Project1].[StudentId] AS [StudentId], 
    [Project1].[FirstName] AS [FirstName], 
    [Project1].[LastName] AS [LastName], 
    [Project1].[StandardId] AS [StandardId], 
    [Project1].[StandardId1] AS [StandardId1], 
    [Project1].[StandardName] AS [StandardName], 
    [Project1].[Description] AS [Description], 
    [Project1].[C1] AS [C1], 
    [Project1].[TeacherId] AS [TeacherId], 
    [Project1].[FirstName1] AS [FirstName1], 
    [Project1].[LastName1] AS [LastName1], 
    [Project1].[StandardId2] AS [StandardId2]
    FROM ( SELECT 
        [Extent1].[StudentId] AS [StudentId], 
        [Extent1].[FirstName] AS [FirstName], 
        [Extent1].[LastName] AS [LastName], 
        [Extent1].[StandardId] AS [StandardId], 
        [Extent2].[StandardId] AS [StandardId1], 
        [Extent2].[StandardName] AS [StandardName], 
        [Extent2].[Description] AS [Description], 
        [Extent3].[TeacherId] AS [TeacherId], 
        [Extent3].[FirstName] AS [FirstName1], 
        [Extent3].[LastName] AS [LastName1], 
        [Extent3].[StandardId] AS [StandardId2], 
        CASE WHEN ([Extent3].[TeacherId] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
        FROM   [dbo].[Student] AS [Extent1]
        LEFT OUTER JOIN [dbo].[Standard] AS [Extent2] ON [Extent1].[StandardId] = [Extent2].[StandardId]
        LEFT OUTER JOIN [dbo].[Teacher] AS [Extent3] ON [Extent3].[StandardId] = [Extent1].[StandardId]
    )  AS [Project1]
    ORDER BY [Project1].[StudentId] ASC, [Project1].[StandardId1] ASC, [Project1].[C1] ASC
Example:

In the following example, we Load one Student and its related address and Standard.

using System;
using System.Linq;
using System.Data.Entity;
namespace DBFirstApproach
{
    class Program
    {
        static void Main(string[] args)
        {
            using (EF_Demo_DBEntities context = new EF_Demo_DBEntities())
            {
                var student = context.Students
                               .Include("Standard")
                               .Include(x => x.StudentAddress)
                               .FirstOrDefault(s => s.StandardId == 1);

                Console.WriteLine($"Firstname: {student.FirstName}, Lastname: {student.LastName}, StandardName: {student.Standard.StandardName}, Description: {student.Standard.Description}, AddresLin1 {student.StudentAddress.Address1}, AddresLin2 {student.StudentAddress.Address2}");

                Console.Read();
            }
        }
    }
}

When we execute the above program, the following SQL Script will be generated and executed in the database.

Eager Loading in Entity Framework with Examples

When to use Eager Loading in Entity Framework?
  1. Generally, when the relations between the entities are not too much, use Eager Loading. 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.

In the next article, I am going to discuss Lazy Loading in Entity Framework. In this article, I try to explain Eager Loading in Entity Framework with Examples and I hope you enjoyed this Eager Loading in Entity Framework article. Please give your valuable feedback and suggestions about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *