Eager , Lazy and explicit loading in EF6

后端 未结 3 1211
我寻月下人不归
我寻月下人不归 2020-11-30 01:02

I have read this tutorial and this article but I don\'t understand exactly the use of each loading type.

I Explain

I have this POCO :

<
3条回答
  •  独厮守ぢ
    2020-11-30 01:39

    Here you will learn how to load related entities in an entity graph explicitly. Explicit loading is valid in EF 6 and EF Core both.

    Even with lazy loading disabled (in EF 6), it is still possible to lazily load related entities, but it must be done with an explicit call. Use the Load() method to load related entities explicitly. Consider the following example.

    using (var context = new SchoolContext())
    {
         var student = context.Students
                                  .Where(s => s.FirstName == "Bill")
                                 .FirstOrDefault();
    
         context.Entry(student).Reference(s => s.StudentAddress).Load(); 
         // loads StudentAddress
         context.Entry(student).Collection(s => s.StudentCourses).Load(); 
         // loads Courses collection      
    }
    

    In the above example, context.Entry(student).Reference(s => s.StudentAddress).Load() loads the StudentAddress entity. The Reference() method is used to get an object of the specified reference navigation property and the Load() method loads it explicitly.

    In the same way, context.Entry(student).Collection(s => s.Courses).Load() loads the collection navigation property Courses of the Student entity. The Collection() method gets an object that represents the collection navigation property.

    The Load() method executes the SQL query in the database to get the data and fill up the specified reference or collection property in the memory, as shown below.
    Query(): You can also write LINQ-to-Entities queries to filter the related data before loading. The Query() method enables us to write further LINQ queries for the related entities to filter out related data.

    using (var context = new SchoolContext())
    {
        var student = context.Students
                        .Where(s => s.FirstName == "Bill")
                        .FirstOrDefault();
    
        context.Entry(student)
                 .Collection(s => s.StudentCourses)
                   .Query()
                .Where(sc => sc.CourseName == "Maths")
                .FirstOrDefault();
    }     
    

    In the above example, .Collection(s => s.StudentCourses).Query() allows us to write further queries for the StudentCourses entity.

提交回复
热议问题