CodexBloom - Programming Q&A Platform

LINQ to SQL Query Performance Bottleneck with Large Data Sets in .NET 6

πŸ‘€ Views: 353 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-14
c# linq performance dotnet-6 C#

I need help solving I've searched everywhere and can't find a clear answer. I'm currently working with a performance scenario when executing a LINQ to SQL query against a large dataset (over 1 million records) in a .NET 6 application. The query in question uses `GroupBy` to aggregate data based on a foreign key, and it's taking several minutes to execute. Here’s the LINQ query I’m using: ```csharp var result = dbContext.Orders .Where(o => o.OrderDate >= startDate && o.OrderDate <= endDate) .GroupBy(o => o.CustomerId) .Select(g => new { CustomerId = g.Key, TotalOrders = g.Count(), TotalAmount = g.Sum(o => o.Amount) }) .ToList(); ``` I've tried optimizing the query by adding an index on the `OrderDate` and `CustomerId` fields, but it doesn't seem to help much. Additionally, I checked the execution plan and noticed that the query is performing a full table scan despite the indexing. I suspect that the question might be related to how LINQ to SQL translates the query to SQL, but I'm not sure what to look for. Is there a best practice for optimizing LINQ queries when dealing with large datasets? Are there specific LINQ methods or patterns I should avoid that could cause performance degradation? Any suggestions or insights into potential pitfalls would be greatly appreciated. What am I doing wrong? This issue appeared after updating to C# stable. Thanks for any help you can provide! I'm using C# 3.10 in this project. Thanks in advance!