Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

Follow publication

Member-only story

How to Choose the Right Loading Strategy in EF Core?

Jay Krishna Reddy
Stackademic
Published in
3 min readFeb 24, 2025

--

When working with databases or web applications, two common loading strategies are Eager Loading and Lazy Loading. Understanding the difference between these two approaches is crucial for optimizing performance and improving the user experience. In this article, we will explore both concepts with detailed explanations and examples.

What is Eager Loading?

Eager Loading is a technique in which related data is loaded from the database immediately along with the main entity. This approach ensures that all required data is available before any operations are performed on it.

Example of Eager Loading

Consider a scenario where we have two related tables: Customers and Orders. If we need to retrieve customer data along with their orders in Entity Framework (C#), we can use eager loading:

var customersWithOrders = context.Customers.Include(c => c.Orders).ToList();

Line-by-Line Explanation:

  1. context.Customers – Retrieves customer data from the database.
  2. .Include(c => c.Orders) – Fetches related orders along with each customer.
  3. .ToList() – Executes the query and loads the data into memory.

Pros of Eager Loading:

  1. Reduces the number of database queries.
  2. Prevents the N+1 query problem (multiple queries for related entities).
  3. Ensures all required data is available at once.

Cons of Eager Loading:

  1. Can lead to over-fetching (loading more data than necessary).
  2. Increases memory usage if the dataset is large.

What is Lazy Loading?

Lazy Loading is a technique where related data is loaded only when it is needed. This means that the main entity is retrieved first, and associated data is fetched later when accessed.

Example of Lazy Loading

Using the same Customers and Orders example in Entity Framework:

var customers = context.Customers.ToList();

foreach (var customer in customers)
{
var orders = customer.Orders; // Orders are loaded only…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

--

--

Published in Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

Written by Jay Krishna Reddy

✍🏼 Sharing my interesting discoveries about technology

No responses yet

Write a response