CodexBloom - Programming Q&A Platform

Optimizing SQL queries in an ASP.NET application using Entity Framework Core - performance concerns

👀 Views: 41 💬 Answers: 1 📅 Created: 2025-09-13
asp.net entity-framework-core performance sql-optimization C#

I'm dealing with I'm testing a new approach and I'm maintaining legacy code that I'm stuck trying to I tried several approaches but none seem to work..... While refactoring our ASP.NET Core application to improve performance, I've noticed that some of the SQL queries generated by Entity Framework Core are suboptimal. For instance, when fetching a list of users along with their associated roles, EF Core generates multiple joins that seem inefficient. Here's the current LINQ query I've been using: ```csharp var usersWithRoles = await _context.Users .Include(u => u.Roles) .ToListAsync(); ``` The performance has been particularly poor when the user base grows, leading to noticeable delays in data retrieval. I've tried breaking the query into smaller parts, but that led to additional round trips to the database: ```csharp var users = await _context.Users.ToListAsync(); foreach (var user in users) { user.Roles = await _context.UserRoles.Where(ur => ur.UserId == user.Id).ToListAsync(); } ``` This approach didn’t yield the expected performance gains and instead introduced complexity. Additionally, I've considered using raw SQL queries for finer control, but I’m concerned about maintainability and security issues, especially with SQL injection risks. Here’s how I attempted it: ```csharp var usersWithRolesRaw = await _context.Users.FromSqlRaw("SELECT * FROM Users u JOIN UserRoles ur ON u.Id = ur.UserId").ToListAsync(); ``` Is there a recommended strategy or best practices for optimizing such queries using EF Core? Perhaps there’s a way to tweak the `Include` method, or should I explore using projections with `Select` instead? Any insights or examples would be greatly appreciated, especially concerning performance tuning and reducing the generated SQL complexity. For context: I'm using C# on Ubuntu. Is there a better approach? What am I doing wrong? Has anyone dealt with something similar? I'm on Linux using the latest version of C#. Thanks in advance!