CodexBloom - Programming Q&A Platform

Struggling with Entity Framework Core Lazy Loading and Performance in ASP.NET Core 6 MVP

πŸ‘€ Views: 80 πŸ’¬ Answers: 1 πŸ“… Created: 2025-09-06
asp.net-core entity-framework-core performance csharp

I'm working through a tutorial and I'm working on a personal project and Currently developing a minimum viable product using ASP.NET Core 6 and Entity Framework Core, and I've run into a performance issue related to lazy loading... My application fetches data from a SQL Server database, and while I appreciate the convenience of lazy loading for related entities, the performance hits are becoming noticeable as my dataset grows. I have the following data model: ```csharp public class Product { public int Id { get; set; } public string Name { get; set; } public ICollection<Category> Categories { get; set; } } public class Category { public int Id { get; set; } public string Name { get; set; } } ``` When I retrieve a list of products, I simply use: ```csharp var products = await _context.Products.ToListAsync(); ``` But later, when I try to access the categories for each product in the view, I notice multiple database calls being made, causing a significant delay: ```html @foreach (var product in products) { <div>@product.Name</div> <ul> @foreach (var category in product.Categories) { <li>@category.Name</li> } </ul> } ``` To mitigate this, I tried eager loading by modifying my query like so: ```csharp var products = await _context.Products.Include(p => p.Categories).ToListAsync(); ``` However, this still feels suboptimal since if the categories collection grows large, I fear it could lead to loading too much unnecessary data. While looking for best practices, it seems like I should be implementing a projection to only retrieve the data I need. I attempted the following with a DTO: ```csharp var products = await _context.Products .Select(p => new { p.Name, Categories = p.Categories.Select(c => c.Name) }) .ToListAsync(); ``` This works fine, but I'm still not sure if it’s the most efficient approach, especially as more complex relationships are introduced in the future. Is there a better way to handle lazy loading vs eager loading in this context, or specific strategies I might be overlooking for optimizing performance in ASP.NET Core with EF Core? Any insights or recommendations would be greatly appreciated! My development environment is Ubuntu. I'm on Ubuntu 20.04 using the latest version of Csharp. Any suggestions would be helpful. I'm using Csharp latest in this project.