Entity Framework - Explicit Loading



When you disabled the lazy loading, it is still possible to lazily load related entities, but it must be done with an explicit call.

  • Unlike lazy loading, there is no ambiguity or possibility of confusion regarding when a query is run.

  • To do so you use the Load method on the related entity’s entry.

  • For a one-to-many relationship, call the Load method on Collection.

  • And for a one-to-one relationship, call the Load method on Reference.

Let’s take a look at the following example in which lazy loading is disabled and then the student whose first name is Ali is retrieved.

Student information is then written on console. If you look at the code, enrollments information is also written but Enrollments entity is not loaded yet so foreach loop will not be executed.

After that Enrollments entity is loaded explicitly now student information and enrollments information will be written on the console window.

class Program {

   static void Main(string[] args) {

      using (var context = new UniContextEntities()) {

         context.Configuration.LazyLoadingEnabled = false;

         var student = (from s in context.Students where s.FirstMidName == 
            "Ali" select s).FirstOrDefault<Student>();

         string name = student.FirstMidName + " " + student.LastName;
         Console.WriteLine("ID: {0}, Name: {1}", student.ID, name);

         foreach (var enrollment in student.Enrollments) {
            Console.WriteLine("Enrollment ID: {0}, Course ID: {1}", 
               enrollment.EnrollmentID, enrollment.CourseID);
         }

         Console.WriteLine();
         Console.WriteLine("Explicitly loaded Enrollments");
         Console.WriteLine();

         context.Entry(student).Collection(s ⇒ s.Enrollments).Load();
         Console.WriteLine("ID: {0}, Name: {1}", student.ID, name);

         foreach (var enrollment in student.Enrollments) {
            Console.WriteLine("Enrollment ID: {0}, Course ID: {1}", 
               enrollment.EnrollmentID, enrollment.CourseID);
         }

         Console.ReadKey();
      }
   }
}

When the above example is executed, you will receive the following output. First only student information is displayed and after explicitly loading enrollments entity, both student and his related enrollments information is displayed.

ID: 1, Name: Ali Alexander
Explicitly loaded Enrollments
ID: 1, Name: Ali Alexander
       Enrollment ID: 1, Course ID: 1050
       Enrollment ID: 2, Course ID: 4022
       Enrollment ID: 3, Course ID: 4041

We recommend that you execute the above example in a step-by-step manner for better understanding.

Advertisements