CodexBloom - Programming Q&A Platform

Performance Issues with Entity Framework Core 6 When Using Complicated LINQ Queries

👀 Views: 3 💬 Answers: 1 📅 Created: 2025-06-06
entity-framework linq performance C#

I'm stuck on something that should probably be simple. Hey everyone, I'm running into an issue that's driving me crazy... I'm experiencing significant performance bottlenecks when using Entity Framework Core 6 to execute complex LINQ queries involving multiple joins and projections. The query I'm using seems efficient at first glance, but the execution time is unacceptably long, especially with larger datasets. Here’s a simplified version of the query: ```csharp var result = await context.Orders .Include(o => o.Customer) .Include(o => o.OrderItems) .ThenInclude(oi => oi.Product) .Where(o => o.OrderDate >= startDate && o.OrderDate <= endDate) .Select(o => new { o.OrderId, CustomerName = o.Customer.Name, TotalAmount = o.OrderItems.Sum(oi => oi.Quantity * oi.Product.Price) }) .ToListAsync(); ``` I've tried optimizing this by ensuring that indexes are placed correctly on the database level and reducing the number of included entities, but the response time is still around 7-10 seconds for a dataset with about 10,000 orders. I also attempted to enable `AsNoTracking()` to improve performance, but it didn’t help much. While profiling the SQL generated by EF Core, I noticed that it’s generating a complex query with multiple nested selects, which might be the cause of the slowdown. Here’s the SQL it generates: ```sql SELECT o.OrderId, c.Name as CustomerName, SUM(oi.Quantity * p.Price) as TotalAmount FROM Orders o JOIN Customers c ON o.CustomerId = c.CustomerId JOIN OrderItems oi ON o.OrderId = oi.OrderId JOIN Products p ON oi.ProductId = p.ProductId WHERE o.OrderDate BETWEEN @startDate AND @endDate GROUP BY o.OrderId, c.Name; ``` I’m trying to figure out if there’s a better way to structure my LINQ query to enhance performance, or if there are any specific flags or settings in EF Core that can help with large datasets like this. Any insights or recommendations would be greatly appreciated! My development environment is macOS. Thanks in advance! My development environment is Debian. Any ideas how to fix this?