Eager vs Lazy Loading in C#

When working with data (like in Entity Framework or any ORM), how objects are loaded from the database matters. There are two main strategies:

Eager Loading

Definition: Loads all related data at once, even if you don’t need it immediately.

Pros: Less database round-trips. Good when you know you will need the data.

Cons: Can load unnecessary data, making queries slower or heavier.

// Example using Entity Framework
using (var context = new SchoolContext())
{
    // Eager loading with Include()
    var students = context.Students
                          .Include(s => s.Courses)
                          .ToList();

    // Here, Students and their Courses are loaded together
}

Lazy Loading

Definition: Loads related data only when it is accessed, not upfront.

Pros: Saves memory and avoids loading unused data.

Cons: Can cause multiple database calls (N+1 problem).

// Example using Entity Framework with Lazy Loading
public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    // virtual enables lazy loading
    public virtual ICollection<Course> Courses { get; set; }
}

using (var context = new SchoolContext())
{
    var student = context.Students.First();

    // Courses are not loaded yet
    var courseList = student.Courses; // Now EF loads them when accessed
}

Quick Comparison