When building web APIs, data efficiency is crucial. If your app retrieves more data than needed, it affects memory, speed, and even user experience. Lazy Loading is a smart strategy that allows you to defer the loading of related data until you actually need it.
In this article, we’ll walk through everything you need to know about Lazy Loading in ASP.NET Core Web API using Entity Framework Core with a full implementation example.
What is Lazy Loading?
Lazy Loading is a technique where related data is not loaded from the database until it is specifically requested. This helps in reducing the initial loading time and memory usage of an application.
In EF Core, Lazy Loading works by intercepting access to navigation properties and loading them only when they’re used.
Comparison Table
Loading Type | Definition | When to Use |
---|---|---|
Eager Loading | Load related data immediately using.Include() | You know you’ll need related data |
Lazy Loading | Load related data only when it’s accessed | You don’t always need related data |
Explicit Loading | Manually load related data via code | You want full control |
Step 1. Create a New ASP.NET Core Web API Project.
Step 2. Install Required NuGet Packages.
Step 3. Define Your Models.
Models/Product.cs
Models/Category.cs
Step 4. Create DbContext and Enable Lazy Loading.
Data/AppDbContext.cs
Step 5. Register DbContext in Program.cs.
Add the connection string in appsettings.json.
Step 6. Create and Apply Migrations.
Step 7. Create DTOs to Avoid Infinite Loops.
DTOs/ProductDto.cs
Step 8. Create an API Controller.
Controllers/ProductsController.cs
Step 9. Seed Sample Data (Optional).
Add this to the Program.cs before app.Run().
Test with Swagger or Postman