Entity Framework - Explicit Loading


It is still possible to lazy load related entities even if lazy loading is disabled, but it must be done with an explicit call. To do so use Load method in the related entity's entry.

Reference method should be used when an entity has a navigation property to another single entity.
You can explicitly load a navigation property via the DbContext.Entry(...) API. 

For example:

using (var context = new BooksContext()) 
{ 
    var publisher = context.Publisher.Find(2); 
 
    // Load the books related to a given publisher 
    context.Entry(publisher).Reference(p => p.Book).Load(); 
 
    // Load the book related to a given publisehr using a string  
    context.Entry(publisher).Reference("Book").Load(); 
 
    var book = context.Books.Find(1); 
 
    // Load the publishers related to a given book 
    context.Entry(book).Collection(p => p.Publisher).Load(); 
 
    // Load the publishers related to a given book using a string to specify the relationship 
    context.Entry(book).Collection("Publisher").Load(); 
}

Applying filters when explicitly loading related entities
Query method provides access to the underlying query that Entity Framework will use when loading related entities. You can then use LINQ to apply filters to the query before executing it with a call to a LINQ extension method such as ToList, Load, etc. Query method can be used with both reference and collection navigation properties but is most useful for collections where it can be used to load only part of the collection. 

For example:

using (var context = new BooksContext()) 
{ 
    var book = context.Books.Find(1); 
 
    // Load the publisher with the Entity-Framework tag related to a given book 
        context.Entry(book) 
        .Collection(b => b.Ppublisher) 
        .Query() 
        .Where(p => p.Tags.Contains("Entity-Framework") 
        .Load(); 
 
    // Load the publishers with the 'Entity-Framework' tag related to a given book using a string to specify the relationship  
        context.Entry(book) 
        .Collection("Publishers") 
        .Query() 
        .Where(p => p.Tags.Contains("Entity-Framework") 
        .Load(); 
}

It is best to turn off lazy loading for the navigation property when using the Query method. If not then entire collection may get loaded automatically by the lazy loading mechanism either before or after the filtered query has been executed.
 

Praesent mattis

Pellentesque viverra vulputate enim. Aliquam erat volutpat. Pellentesque tristique ante ut risus. Quisque dictum. Integer nisl risus, sagittis convallis, rutrum id, elementum congue, nibh. Suspendisse dictum porta lectus. Donec placerat odio vel elit.

Read More