English 中文(简体)
Entity Framework Tutorial

Entity Framework Resources

Selected Reading

Entity Framework - Explicit Loading
  • 时间:2024-11-03

Entity Framework - Exppcit Loading


Previous Page Next Page  

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

    Unpke lazy loading, there is no ambiguity or possibipty 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 Ap 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 exppcitly 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 == 
            "Ap" 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("Exppcitly 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 exppcitly loading enrollments entity, both student and his related enrollments information is displayed.

ID: 1, Name: Ap Alexander
Exppcitly loaded Enrollments
ID: 1, Name: Ap 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