Lazy vs Eager Loading


There are two different strategies for loading related data in applications. They are commonly used in Object-Relational Mapping (ORM) frameworks and database access patterns.

  1. Lazy Loading
  2. Eager Loading

1. Lazy Loading

Lazy loading delays the loading of related data until it is specifically needed. This can improve performance by loading data only when it's accessed, rather than at the initial query.

OR

Data is loaded on demand. It’s useful when you have a large dataset and want to minimize the initial load time. However, it can result in multiple database queries if related data is accessed frequently.

Example

Suppose you have two entities, Author and Book, where an author can have multiple books.

public class Author
{
    public int AuthorId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Book> Books { get; set; }
}

public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public int AuthorId { get; set; }
    public virtual Author Author { get; set; }
}

If Books property is marked as virtual, Entity Framework will use lazy loading by default. Here’s how it works.

using (var context = new MyDbContext())
{
    var author = context.Authors.FirstOrDefault(a => a.AuthorId == 1);
    // Books are not loaded yet
    var books = author.Books; // Books are loaded when this line is executed
}

2. Eager Loading

Eager loading loads all the related data at the same time as the primary data. This can be beneficial when you know you will need the related data and want to reduce the number of queries to the database.

OR

Data is loaded upfront with the initial query. It’s useful when you need the related data immediately.

Note - Eager loading does not require the virtual keyword. Eager loading is a mechanism where related data is loaded along with the main entity in a single query. This is achieved using the Include method in Entity Framework.

Example

Using the same Author and Book entities, you can use eager loading with the Include method.

using (var context = new MyDbContext())
{
    var author = context.Authors
                        .Include(a => a.Books) // Eagerly loads related Books
                        .FirstOrDefault(a => a.AuthorId == 1);
    // Books are already loaded above
    var books = author.Books;
}

Choosing between lazy and eager loading depends on your specific use case and performance considerations.

Key Differences

  • Lazy Loading - Requires virtual keyword to enable proxy-based loading of related data on demand.
  • Eager Loading - Does not require virtual. Uses the Include method to load related data along with the initial query.

Prev Next