Introduction
In an ASP.NET Core application, query performance is not determined only by the C# code. A LINQ expression is translated into SQL by EF Core, and SQL Server executes that statement through operations such as table scans, index seeks, sorting, and joins. For this reason, looking only at the LINQ expression is often insufficient. A reliable investigation combines the generated SQL, the parameters, and the execution plan selected by SQL Server.
In this lesson, we will analyze a product-listing query. We will first inspect the SQL generated by EF Core, then use logging and ToQueryString to understand the translation. Next, we will examine the execution plan in SQL Server Management Studio and create indexes for filtering and sorting. Finally, we will compare measurements before and after the index is added.
1. The query we will analyze
Assume that a product list filters products by category and name, returns only the required columns, and orders the result by name. Because the screen does not need the complete entity, the query uses a projection.
var query = dbContext.Products
.AsNoTracking()
.Where(p => p.IsActive
&& p.CategoryId == categoryId
&& p.Name.StartsWith(searchText))
.OrderBy(p => p.Name)
.Select(p => new ProductListItem
{
Id = p.Id,
Name = p.Name,
Price = p.Price,
CategoryId = p.CategoryId
});
var products = await query.ToListAsync(cancellationToken);This query has three important performance dimensions. IsActive and CategoryId participate in filtering, while Name participates in both text search and ordering. A prefix search with StartsWith can be more compatible with a conventional index than a suffix search such as EndsWith. The actual result still depends on the database schema, data distribution, collation, and parameter values.
2. Viewing SQL generated by EF Core
Using ToQueryString
The ToQueryString method returns a string representation of the SQL that an EF Core LINQ query is expected to execute. It is useful for discovering whether a query is translated as intended.
var sql = query.ToQueryString();
Console.WriteLine(sql);Depending on the EF Core version and provider, the output will differ slightly. For SQL Server, it will generally resemble the following:
SELECT [p].[Id], [p].[Name], [p].[Price], [p].[CategoryId]
FROM [Products] AS [p]
WHERE [p].[IsActive] = CAST(1 AS bit)
AND [p].[CategoryId] = @__categoryId
AND [p].[Name] LIKE @__searchText_startswith
ORDER BY [p].[Name]ToQueryString is intended for diagnostics and debugging. It should not be treated as a replacement for application query execution or blindly copied into production code. Parameter values may not appear in the returned string, so runtime logging and database tools are still needed to understand actual behavior.
Enabling safe development logging
EF Core integrates with the Microsoft.Extensions.Logging infrastructure used by ASP.NET Core. During development, SQL command logging can be enabled in appsettings.Development.json.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.EntityFrameworkCore.Database.Command": "Information"
}
}
}For a development-only diagnostic setup, logging can also be configured when building the DbContext:
optionsBuilder
.EnableDetailedErrors()
.LogTo(Console.WriteLine, LogLevel.Information);When command logging is enabled, you can inspect the executed SQL, parameters, and elapsed time. Sensitive data must be handled carefully. Search terms, email addresses, tokens, and other user-provided values should not be written to production logs without an explicit privacy and security decision. Detailed SQL logging is usually best limited to development, testing, or controlled diagnostics.
3. Reading a SQL Server execution plan
Seeing the SQL statement does not explain exactly why it is slow. An execution plan shows how SQL Server intends to access the data and perform operations. It can reveal whether the server scans a table, seeks through an index, performs an additional sort, or looks up missing columns.
In SQL Server Management Studio, select Display Estimated Execution Plan before execution, or enable Include Actual Execution Plan and then run the statement. The actual plan includes runtime information such as actual row counts, but it also executes the query and should therefore be used deliberately.
When reading a plan, examine the following operators and signals:
- Table Scan: SQL Server reads a broad portion of the table. This may be reasonable for a small table, but should be investigated on large tables.
- Index Seek: The engine can navigate to a targeted range of index entries.
- Index Scan: A large part of an index is read. It is not automatically wrong, but can become expensive when many rows are touched.
- Sort: Results are sorted as a separate operation. An index whose key order matches the query may reduce this work.
- Key Lookup: SQL Server uses an index to find rows, then accesses the base table to retrieve columns missing from that index.
- Estimated versus actual rows: Large differences may indicate stale statistics, skewed data, parameter sensitivity, or a query shape that is difficult to estimate.
Plan percentages should not be treated as final performance measurements. They are cost estimates within a plan. Elapsed time, CPU time, logical reads, result size, and repeated measurements provide stronger evidence.
4. Designing an appropriate index
An index can accelerate searches and ordering over selected columns, but every index has a cost. Indexes consume storage and must be maintained during inserts, updates, and deletes. The goal is not to add as many indexes as possible; it is to support important access patterns with a small, justified set of indexes.
In our example, the query filters by category and active status, then searches and orders by product name. A possible SQL Server index is:
CREATE INDEX IX_Products_CategoryId_IsActive_Name
ON dbo.Products (CategoryId, IsActive, Name)
INCLUDE (Price);The key order matters. In a composite index, leading columns strongly influence which queries can use the index efficiently. Here, CategoryId and IsActive represent equality filters, while Name supports the search and ordering pattern. Price is returned but not used for filtering, so it may be considered as an included column. This is a starting hypothesis, not a universal rule. Data distribution and real workload measurements must confirm the design.
The same index can be represented in the EF Core model:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>()
.HasIndex(p => new { p.CategoryId, p.IsActive, p.Name })
.HasDatabaseName("IX_Products_CategoryId_IsActive_Name");
}After adding the model configuration, create and apply a migration:
dotnet ef migrations add AddProductSearchIndex
dotnet ef database updateBefore applying an index change to production, evaluate its build time, locking behavior, storage impact, and effect on write-heavy workloads. On large tables, index operations may need to be scheduled during an appropriate maintenance window.
5. Comparing performance before and after indexing
An optimization should not be considered successful merely because an execution plan displays Index Seek. Compare the same query, with the same parameters, against the same data under reasonably similar server conditions.
- Run the query before adding the index.
- Separate the first execution as a warm-up because plan and data caches can affect results.
- Record elapsed time, CPU time, and logical reads.
- Save the actual execution plan.
- Create the index and ensure that relevant statistics are appropriate.
- Run the same query again with the same parameters.
- Compare both the measurements and the execution plans.
SQL Server can report IO and timing information with the following commands:
SET STATISTICS IO ON;
SET STATISTICS TIME ON;
SELECT Id, Name, Price, CategoryId
FROM dbo.Products
WHERE IsActive = 1
AND CategoryId = 4
AND Name LIKE N'Lap%'
ORDER BY Name;
SET STATISTICS TIME OFF;
SET STATISTICS IO OFF;After indexing, logical reads may decrease, CPU and elapsed time may improve, or the plan may change from a table scan to an index seek. However, SQL Server may still choose a scan when the table is small or when the query returns a large percentage of the rows. That is not automatically a failure; the optimizer is comparing estimated total costs for the specific query.
6. Common mistakes
- Looking only at LINQ: Without checking generated SQL and the execution plan, optimization decisions may be based on incorrect assumptions.
- Indexing every column: Excessive indexes increase storage, maintenance, and write costs.
- Applying functions to columns: Expressions such as
Where(p => p.Name.ToLower() == value)can make ordinary indexes harder to use. Case and collation requirements should be designed deliberately. - Confusing prefix and contains searches:
Containssearches anywhere in a string and may be less compatible with a conventional index than a prefix search. - Treating plan percentages as runtime: A percentage is an estimated cost share inside one plan, not the application's actual response time.
- Leaving verbose SQL logging enabled in production: This can create large log volumes, performance overhead, and data exposure risks.
- Expecting an index seek every time: A scan can be the better choice for small tables or queries returning many rows.
7. Short practice exercise
Complete the following exercise in the ASP.NET Core project:
- Print the product-listing query with
ToQueryString. - Enable EF Core database-command logging only in the Development environment.
- Open the actual execution plan for the equivalent SQL in SSMS.
- Record
SET STATISTICS IO ONandSET STATISTICS TIME ONresults before adding an index. - Create an index with
(CategoryId, IsActive, Name)as key columns andPriceas an included column. - Run the same query again and compare the plan, logical reads, and timing.
- Compare
Name.Contains(searchText)withName.StartsWith(searchText)and explain why their plans may differ.
Conclusion
EF Core query analysis is more than rewriting a LINQ expression. A dependable process includes inspecting generated SQL, reviewing parameters and logs, examining the SQL Server execution plan, designing indexes for real access patterns, and measuring the result before and after the change.
Indexes can provide substantial improvements for the right workload, but adding indexes randomly is not a sustainable strategy. Projection, database-side filtering, search expressions that match the indexing strategy, and repeatable measurements should be applied together. In the next lessons, we will extend this approach to the N+1 problem, related-data loading, and more advanced EF Core query optimizations.
Sources
- https://learn.microsoft.com/en-us/ef/core/performance/efficient-querying
- https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/
- https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.entityframeworkqueryableextensions.toquerystring
- https://learn.microsoft.com/en-us/ef/core/modeling/indexes
- https://learn.microsoft.com/en-us/sql/relational-databases/performance/execution-plans
- https://learn.microsoft.com/en-us/sql/relational-databases/performance/compare-and-analyze-execution-plans