CodexBloom - Programming Q&A Platform

Performance Degradation when Using Entity Framework Core with Lazy Loading in .NET 6

👀 Views: 3 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-05
entity-framework-core lazy-loading performance C#

Does anyone know how to I'm performance testing and I'm working on a personal project and I just started working with I'm experiencing significant performance issues in my .NET 6 application when using Entity Framework Core with lazy loading enabled..... The application runs fine with eager loading, but as soon as I switch to lazy loading, the time taken for certain queries skyrockets, leading to timeouts. For instance, I have an `Order` entity that includes a collection of `OrderItems`. When I try to access the `OrderItems` property of an `Order` instance with lazy loading, it takes about 3-4 seconds instead of the usual 200ms. I have the following models: ```csharp public class Order { public int Id { get; set; } public virtual ICollection<OrderItem> OrderItems { get; set; } } public class OrderItem { public int Id { get; set; } public int OrderId { get; set; } public string ProductName { get; set; } } ``` And in my `DbContext`, I have: ```csharp public class MyDbContext : DbContext { public DbSet<Order> Orders { get; set; } public DbSet<OrderItem> OrderItems { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Order>() .HasMany(o => o.OrderItems) .WithOne() .HasForeignKey(oi => oi.OrderId); } } ``` I have ensured that lazy loading is enabled in the `Startup` configuration: ```csharp services.AddDbContext<MyDbContext>(options => options.UseLazyLoadingProxies().UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); ``` I've tried profiling the database queries using SQL Server Profiler, and I noticed that each access to `OrderItems` results in a separate query being executed for every order, significantly increasing the number of queries. Is there a way to optimize lazy loading performance, or is it generally recommended to stick with eager loading for scenarios like this? Any advice or best practices would be greatly appreciated! This is part of a larger CLI tool I'm building. I'd really appreciate any guidance on this. What's the correct way to implement this? The project is a service built with C#. Any feedback is welcome! I recently upgraded to C# 3.10. My development environment is Windows 11. Any ideas what could be causing this?