Entity Framework - Lazy Loading


Lazy loading is the process where an entity or collection of entities is automatically loaded from the database the first time that a property referring to the entity/entities is accessed. When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook.

The alternative (and default) strategy for the EF is a lazy loading strategy. With lazy loading, EF loads only the data for the primary object in the LINQ query and leaves the Contact object.

Lazy loading brings in the related data on an as-needed basis, meaning when something touches the Contact property of a Friend, EF loads the data by sending an additional query to the database.

For example, when using the Book entity class defined, the related Publisher will be loaded the first time the Publisher navigation property is accessed:

public class Book 
{  
    public int BookId { get; set; }  
    public string Name { get; set; }  
    public string Pages { get; set; }  
 
    public virtual ICollection Publishers { get; set; }  
}

Turning off lazy loading for specific navigation properties
Lazy loading of the Publisher collection can be turned off by making the Publisher property non-virtual:

public class Blog 
{  
    public int BookId { get; set; }  
    public string Name { get; set; }  
    public string Pages { get; set; }  
 
    public ICollection Publishers { get; set; }  
}

Turn off lazy loading for all entities
Lazy loading can be turned off for all entities in the context by setting a flag on the Configuration property.
For example:

public class BooksContext : DbContext 
{ 
    public BooksContext() 
    { 
        this.Configuration.LazyLoadingEnabled = false; 
    } 
}

 

 

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