Redis :👈 👉:Database-Transaction-Management

EF Core Advanced Query Optimization: Execution Plans, N+1 and Compiled Queries

EF Core Advanced Query Optimization

Execution Plans, N+1 Queries, Compiled Queries, Indexing, Query Translation and Production Performance

1. Introduction

Entity Framework Core (EF Core) is an Object-Relational Mapper (ORM) that allows .NET applications to interact with relational databases using C# objects and LINQ queries.

EF Core simplifies database development, but poorly designed queries can cause serious performance problems.

Common performance problems include:

  • Unnecessary database queries.
  • N+1 query problems.
  • Missing database indexes.
  • Loading unnecessary columns.
  • Loading too many records into memory.
  • Unnecessary entity tracking.
  • Expensive joins and subqueries.
  • Repeated query compilation overhead.
  • Incorrect pagination.
  • Database execution plans that perform table scans.

Query optimization means reducing database work, network traffic, memory consumption, and application processing time while preserving the correctness of the results.

2. How EF Core Executes a LINQ Query

When you write a LINQ query, EF Core does not immediately execute it. It first builds an expression representation of the query.

EF Core translates the expression into SQL that the database provider understands.

Query Execution Flow

C# LINQ Query Expression Tree EF Core Query Translation Generated SQL Query Database Execution Results Materialized in C#

Example LINQ Query

var products = await dbContext.Products
    .Where(p => p.Price > 1000)
    .OrderBy(p => p.Name)
    .ToListAsync();

Equivalent SQL Concept

SELECT *
FROM Products
WHERE Price > 1000
ORDER BY Name;

The actual generated SQL depends on the database provider, model configuration, and EF Core version.

3. Understanding Deferred Execution

LINQ queries in EF Core generally use deferred execution. This means the query is constructed first and executed only when an operation requests the results.

Query Construction

var query = dbContext.Products
    .Where(p => p.Price > 1000)
    .OrderBy(p => p.Name);

At this point, the database query has generally not executed.

Query Execution

var products = await query.ToListAsync();

ToListAsync() executes the query and materializes the returned records.

Other common execution methods include:

Method Purpose
ToListAsync() Loads all matching records into a list.
FirstOrDefaultAsync() Returns the first matching record or null.
SingleOrDefaultAsync() Returns zero or one matching record; throws if multiple records match.
AnyAsync() Checks whether at least one matching record exists.
CountAsync() Returns the number of matching records.
SumAsync() Calculates the sum of a numeric value.
ToDictionaryAsync() Materializes results into a dictionary.

Optimization tip: Do not execute the same IQueryable multiple times unnecessarily. Each terminal operation may issue another database query.

4. Understanding SQL Execution Plans

A SQL execution plan describes how the database engine intends to retrieve or modify data.

The database optimizer evaluates available indexes, statistics, joins, filters, and estimated costs to select an execution strategy.

Execution plans are important because a LINQ query that looks simple in C# may generate expensive SQL.

Example

var orders = await dbContext.Orders
    .Where(o => o.CustomerId == 100)
    .ToListAsync();

Generated SQL might look similar to:

SELECT *
FROM Orders
WHERE CustomerId = 100;

The database must locate matching rows. It may use an index or scan the table depending on the available indexes, statistics, and estimated costs.

How an Execution Plan Works

SQL Query Database Optimizer Index Seek Find matching index entries Table / Index Scan Read a larger set of rows Simplified illustration: the optimizer chooses the appropriate operators.

The diagram shows two possible access strategies. They are alternatives, not necessarily operations that always occur together.

Important Execution Plan Operators

Operator Meaning Performance Consideration
Index Seek Locates rows using an index. Usually efficient for selective indexed searches.
Index Scan Reads index entries. May be efficient or expensive depending on the number of rows read.
Table Scan Reads the table data. Can be expensive for large tables.
Key Lookup Retrieves additional columns from the base table using an index key. Many repeated lookups can become expensive.
Nested Loops Joins rows by repeatedly searching the inner input. Can be efficient for small inputs, but expensive for large inputs.
Hash Match Uses a hash structure for joins or aggregation. Can consume memory and may spill to disk.
Sort Sorts records. Can be expensive for large datasets.
Filter Applies a filtering condition. Check whether the filtering work can be reduced earlier.
Stream Aggregate Aggregates ordered input. Can be efficient when input is already suitably ordered.

Important: An Index Seek is not automatically better than an Index Scan. The correct plan depends on selectivity, table size, row width, statistics, and the cost of accessing the data.

5. How to View SQL Execution Plans in SQL Server

When using SQL Server, you can inspect execution plans through SQL Server Management Studio (SSMS).

Method 1: Actual Execution Plan

  1. Open SQL Server Management Studio.
  2. Connect to your database.
  3. Open a new query window.
  4. Write your SQL query.
  5. Select Include Actual Execution Plan or press Ctrl + M.
  6. Execute the query.
  7. Open the Execution Plan tab.
  8. Inspect the operators, warnings, and estimated versus actual row counts.

Method 2: Estimated Execution Plan

The estimated execution plan shows the plan selected by the optimizer without executing the query.

In SSMS, select Display Estimated Execution Plan or press Ctrl + L.

Actual vs Estimated Execution Plan

Feature Estimated Plan Actual Plan
Executes query No Yes
Shows actual row counts No Yes
Shows runtime information No Yes
Useful for Inspecting the optimizer's planned operations Finding actual runtime problems

Method 3: IO and Time Statistics

SQL Server can report how much data was read and how long query execution took.

SET STATISTICS IO ON;
SET STATISTICS TIME ON;
SELECT *
FROM Orders
WHERE CustomerId = 100;
SET STATISTICS IO OFF;
SET STATISTICS TIME OFF;

Look for:

  • Logical reads.
  • Physical reads.
  • CPU time.
  • Elapsed time.
  • Large differences between estimated and actual row counts.

6. How to Inspect SQL Generated by EF Core

Before examining the database execution plan, first inspect the SQL generated by EF Core.

Using ToQueryString()

var query = dbContext.Products
    .Where(p => p.Price > 1000)
    .OrderBy(p => p.Name);
var sql = query.ToQueryString();
Console.WriteLine(sql);

ToQueryString() displays a debugging representation of the SQL query. It does not execute the query.

Enable EF Core SQL Logging

builder.Services.AddDbContext<AppDbContext>(options =>
{
    options.UseSqlServer(
        builder.Configuration.GetConnectionString("Default"));
    options.LogTo(
        Console.WriteLine,
        LogLevel.Information);
});

For production, configure structured logging and appropriate log levels. Avoid exposing sensitive parameter values in logs.

Use Query Tags

Query tags help identify which part of your application generated a SQL query.

var products = await dbContext.Products
    .TagWith("ProductCatalog.GetActiveProducts")
    .Where(p => p.IsActive)
    .ToListAsync();

The generated SQL contains a comment identifying the query.

-- ProductCatalog.GetActiveProducts
SELECT ...
FROM Products
WHERE IsActive = 1;

This is useful when investigating SQL Server Query Store data or database logs.

7. Database Indexing for EF Core

An index is a database structure that helps locate rows without scanning every record in a table.

Index design is one of the most important factors in query performance.

Example Table

Imagine an Orders table with these columns:

OrderId
CustomerId
OrderDate
Status
TotalAmount

Query Without a Suitable Index

var orders = await dbContext.Orders
    .Where(o => o.CustomerId == 100)
    .ToListAsync();

If CustomerId has no suitable index, SQL Server may need to scan a large portion of the table.

Create an Index Using EF Core

In the entity configuration:

public class OrderConfiguration :
    IEntityTypeConfiguration<Order>
{
    public void Configure(
        EntityTypeBuilder<Order> builder)
    {
        builder.HasKey(o => o.OrderId);
        builder.HasIndex(o => o.CustomerId);
    }
}

Alternatively, use the data annotation:

[Index(nameof(CustomerId))]
public class Order
{
    public int OrderId { get; set; }
    public int CustomerId { get; set; }
    public DateTime OrderDate { get; set; }
    public string Status { get; set; } = string.Empty;
}

Generate and apply a migration:

dotnet ef migrations add AddCustomerIdIndex
dotnet ef database update

Composite Index

A composite index contains multiple columns.

For example, the following query filters by CustomerId and Status:

var orders = await dbContext.Orders
    .Where(o => o.CustomerId == customerId
        && o.Status == "Completed")
    .ToListAsync();

A possible index is:

builder.HasIndex(o => new
{
    o.CustomerId,
    o.Status
});

Composite index column order matters. The index should be designed around actual query patterns and selectivity.

Covering Index

A covering index contains all the columns needed by a particular query, allowing SQL Server to retrieve the requested data from the index without an additional key lookup.

Example:

var orders = await dbContext.Orders
    .Where(o => o.CustomerId == customerId)
    .Select(o => new OrderSummary
    {
        OrderId = o.OrderId,
        OrderDate = o.OrderDate,
        TotalAmount = o.TotalAmount
    })
    .ToListAsync();

For SQL Server, a possible index definition is:

builder.HasIndex(o => o.CustomerId)
    .IncludeProperties(o => new
    {
        o.OrderId,
        o.OrderDate,
        o.TotalAmount
    });

This can help SQL Server cover the query. Verify the actual execution plan before keeping the index.

Indexing Best Practices

  • Index frequently filtered columns when beneficial.
  • Index columns used in important joins.
  • Consider composite indexes for common combinations of filters and sorting.
  • Use included columns for suitable covering indexes.
  • Avoid creating indexes on every column.
  • Remember that indexes increase storage and write costs.
  • Inspect actual execution plans before adding indexes.

8. SARGability: Write Queries That Can Use Indexes

SARGable means Search ARGument ABLE. A SARGable predicate allows the database optimizer to use an index efficiently when the available index and query conditions support it.

Problem: Applying a Function to an Indexed Column

Consider:

var orders = await dbContext.Orders
    .Where(o => o.OrderDate.Date == selectedDate)
    .ToListAsync();

Depending on the provider and translation, applying a function to the column can make efficient index access harder.

Better Approach: Use a Date Range

var startDate = selectedDate.Date;
var endDate = startDate.AddDays(1);
var orders = await dbContext.Orders
    .Where(o => o.OrderDate >= startDate
        && o.OrderDate < endDate)
    .ToListAsync();

This expresses a range condition directly against OrderDate and can make better use of an index on that column.

Another Example: Leading Wildcard

This query may prevent a conventional B-tree index from efficiently locating matching rows:

var products = await dbContext.Products
    .Where(p => p.Name.Contains("phone"))
    .ToListAsync();

It commonly translates into a pattern similar to:

WHERE Name LIKE '%phone%'

A leading wildcard generally prevents a normal index seek for substring matching.

For large-scale text search, consider SQL Server Full-Text Search or a dedicated search solution, depending on the requirements.

9. N+1 Query Problem

The N+1 query problem is one of the most common EF Core performance issues.

It happens when an application executes one query to retrieve a collection of records and then executes another query for each individual record to retrieve related data.

If the initial query returns N records, the application may execute N+1 database queries.

Example Scenario

Suppose you have:

  • Customers table.
  • Orders table.

One customer can have multiple orders.

Entity Relationship

Customer CustomerId (PK) Name 1 to many Order OrderId (PK) CustomerId (FK)

Bad Example: N+1 Queries

var customers = await dbContext.Customers
    .ToListAsync();
foreach (var customer in customers)
{
    var orders = await dbContext.Orders
        .Where(o => o.CustomerId == customer.CustomerId)
        .ToListAsync();
    Console.WriteLine(
        $"{customer.Name}: {orders.Count}");
}

Suppose there are 100 customers.

The application may execute:

  1. One query to retrieve 100 customers.
  2. 100 additional queries to retrieve each customer's orders.

Total: 101 database queries.

N+1 Execution Diagram

ASP.NET Core Application Query Customers (1) Loop Through Customers Orders Query 1 Customer 1 Orders Query 2 Customer 2 Orders Query N Customer N

Why N+1 Is Expensive

  • Multiple network round trips.
  • Repeated SQL execution.
  • Increased database connection usage.
  • Higher response times.
  • More database CPU and I/O work.
  • Performance becomes worse as the number of parent records increases.

10. How to Fix the N+1 Problem

There are several approaches. The correct one depends on whether you need related entities, a subset of columns, or separate queries.

Solution 1: Eager Loading with Include()

Use Include() when you need the related entity data.

var customers = await dbContext.Customers
    .Include(c => c.Orders)
    .ToListAsync();

This tells EF Core to load customers and their related orders as part of the query operation.

For a collection navigation, EF Core commonly generates a join query by default, although configuration and query shape can change the behavior.

Diagram: Eager Loading

EF Core Include() One SQL Query Operation Customer Data Order Data

Important: Include() can produce a large result set when multiple collection navigations are loaded. This can lead to duplicated data and expensive joins.

Solution 2: Projection with Select()

Projection is often a better approach when an API only needs selected fields.

var customers = await dbContext.Customers
    .Select(c => new CustomerDto
    {
        CustomerId = c.CustomerId,
        Name = c.Name,
        Orders = c.Orders
            .Select(o => new OrderDto
            {
                OrderId = o.OrderId,
                TotalAmount = o.TotalAmount
            })
            .ToList()
    })
    .ToListAsync();

EF Core can translate supported collection projections into SQL. Verify the generated SQL and query behavior for your provider and EF Core version.

Advantages:

  • Loads only required columns.
  • Reduces unnecessary entity materialization.
  • Can reduce data transferred from SQL Server.
  • Produces DTOs directly.
  • Usually avoids unnecessary change tracking for the projected DTO values.

Solution 3: Load Related Data in One Query

If you do not need the entire object graph, you can use a join or projection.

var result = await (
    from customer in dbContext.Customers
    join order in dbContext.Orders
        on customer.CustomerId equals order.CustomerId
    select new
    {
        customer.CustomerId,
        customer.Name,
        order.OrderId,
        order.TotalAmount
    })
    .ToListAsync();

This retrieves a flat result containing customer and order information. Customers without orders are excluded by this inner join.

To include customers without orders, use a left join or an appropriate group join pattern.

Solution 4: Split Queries

When multiple collection navigations are included, a single SQL query can create a large joined result set.

EF Core supports AsSplitQuery() to load related collections through separate SQL queries.

var customers = await dbContext.Customers
    .Include(c => c.Orders)
    .Include(c => c.Addresses)
    .AsSplitQuery()
    .ToListAsync();

Instead of producing one large join across both collections, EF Core executes multiple SQL queries to load the related data.

Benefits:

  • Reduces cartesian multiplication from multiple collection joins.
  • Can reduce repeated parent-column data.
  • Can improve performance for complex object graphs.

Trade-offs:

  • More than one database round trip is required.
  • Multiple queries can observe different database states unless an appropriate transaction and isolation level are used.
  • Performance depends on network latency and result size.

Split queries are not the same as the N+1 problem. They are a deliberate strategy to avoid excessively large joined results.

11. Lazy Loading and Its Performance Risks

Lazy loading retrieves related data only when a navigation property is accessed.

It can be convenient, but it can also introduce hidden database queries.

Example

var customers = await dbContext.Customers
    .ToListAsync();
foreach (var customer in customers)
{
    // May trigger a database query for each customer.
    var orderCount = customer.Orders.Count;
}

If lazy-loading proxies are enabled, accessing customer.Orders may execute a separate SQL query.

Why Lazy Loading Can Cause Problems

  • Database queries are hidden behind property access.
  • It is easy to create N+1 queries accidentally.
  • It can make performance difficult to predict.
  • Serialization of entities can unexpectedly trigger more database queries.

Recommendation: Prefer explicit eager loading or projection for API endpoints where the required data is known in advance.

12. AsNoTracking() for Read-Only Queries

By default, EF Core tracks entities returned from queries. Tracking allows EF Core to detect changes and persist them later through SaveChanges().

However, if you only need to read data, tracking may add unnecessary overhead.

Normal Tracking Query

var products = await dbContext.Products
    .Where(p => p.IsActive)
    .ToListAsync();

EF Core tracks the returned Product entities by default.

Optimized Read-Only Query

var products = await dbContext.Products
    .AsNoTracking()
    .Where(p => p.IsActive)
    .ToListAsync();

AsNoTracking() prevents EF Core from tracking the returned entities.

Tracking vs No Tracking

Feature Tracking No Tracking
Change tracking Yes No
Save modifications automatically detected Yes No
Tracking overhead Higher Lower
Typical use Update operations Read-only operations

AsNoTrackingWithIdentityResolution()

Sometimes a query returns the same entity multiple times because of joins or related data.

AsNoTrackingWithIdentityResolution() allows EF Core to ensure that repeated occurrences of the same entity key use one entity instance within the query result, without tracking those entities in the normal DbContext change tracker.

var customers = await dbContext.Customers
    .Include(c => c.Orders)
    .AsNoTrackingWithIdentityResolution()
    .ToListAsync();

Use this when identity resolution is useful but normal change tracking is not required.

13. Projection: Select Only Required Columns

One of the easiest ways to improve query performance is to avoid retrieving unnecessary columns.

Bad Example

var products = await dbContext.Products
    .ToListAsync();

This retrieves all mapped columns for all matching Product records.

Better Example

var products = await dbContext.Products
    .Select(p => new ProductDto
    {
        Id = p.Id,
        Name = p.Name,
        Price = p.Price
    })
    .ToListAsync();

Only the columns needed by the projection are generally selected.

Why Projection Helps

  • Less data transferred over the network.
  • Less memory used by the application.
  • Less object materialization work.
  • Potentially more efficient covering-index usage.
  • Clear separation between database entities and API response models.

Important: Projection does not automatically make every query fast. The generated SQL and database execution plan still matter.

14. Compiled Queries in EF Core

Compiled queries are an advanced EF Core optimization that can reduce the overhead of processing frequently executed LINQ query expressions.

EF Core normally caches query compilation information. When a query is executed again with the same expression shape, EF Core can often reuse its cached query representation.

However, EF Core still performs work to process the LINQ expression and locate the cached query.

Compiled queries allow you to explicitly compile a query into a reusable delegate.

Normal Query

public async Task<Product?> GetProductAsync(
    int id)
{
    return await _dbContext.Products
        .FirstOrDefaultAsync(p => p.Id == id);
}

EF Core processes the query expression and uses its internal query compilation cache.

Compiled Query

private static readonly Func<
    AppDbContext,
    int,
    Task<Product?>> GetProductByIdCompiled =
        EF.CompileAsyncQuery(
            (AppDbContext context, int id) =>
                context.Products
                    .FirstOrDefault(p => p.Id == id)
        );

Use the compiled delegate:

public Task<Product?> GetProductAsync(int id)
{
    return GetProductByIdCompiled(
        _dbContext,
        id);
}

The compiled query delegate is reused across calls. A different DbContext instance can be passed for each call, provided it uses a compatible model.

Compiled Query Execution Flow

Define LINQ Query EF.CompileAsyncQuery() Reusable Query Delegate Execute with Parameters

Compiled Query with Multiple Parameters

private static readonly Func<
    AppDbContext,
    int,
    bool,
    IAsyncEnumerable<Product>> GetProductsCompiled =
        EF.CompileAsyncQuery(
            (
                AppDbContext context,
                int categoryId,
                bool isActive
            ) =>
                context.Products
                    .Where(p =>
                        p.CategoryId == categoryId
                        && p.IsActive == isActive)
                    .OrderBy(p => p.Name)
        );

Call it:

public async Task<List<Product>> GetProductsAsync(
    int categoryId,
    bool isActive)
{
    var result = new List<Product>();
    await foreach (var product in GetProductsCompiled(
        _dbContext,
        categoryId,
        isActive))
    {
        result.Add(product);
    }
    return result;
}

EF.CompileAsyncQuery() can return an IAsyncEnumerable for a sequence query. The example asynchronously enumerates the returned results.

15. Normal Query Caching vs Compiled Queries

It is important to understand that EF Core already caches query compilation information internally.

Feature Normal LINQ Query Explicit Compiled Query
Query compilation caching Automatic internal cache Explicit reusable delegate
Developer effort Low Higher
Suitable for Most application queries Frequently executed stable query shapes
Performance benefit Uses EF Core's normal optimizations Can reduce some query-processing overhead
Maintenance Simpler Requires managing reusable delegates

Important: Compiled queries do not make SQL Server execute the query faster by themselves. They primarily reduce EF Core-side query processing overhead. Database execution, indexes, network latency, and result materialization may still dominate total execution time.

When Should You Use Compiled Queries?

  • The same query is executed very frequently.
  • The query expression has a stable structure.
  • Application profiling shows EF Core query processing overhead is significant.
  • The application has high-throughput database access patterns.

When Should You Avoid Compiled Queries?

  • The query runs only occasionally.
  • The query changes dynamically in many ways.
  • The database execution time is the actual bottleneck.
  • The additional complexity is not justified by measured performance improvements.

Compiled Query Limitations and Considerations

  • Compiled queries are tied to a specific EF Core model.
  • They work best with simple scalar parameters.
  • Complex parameter expressions and dynamic query shapes require careful design.
  • Use compatible DbContext instances that share the same model.
  • Do not share a DbContext instance across concurrent operations.
  • Benchmark compiled queries against normal queries before adopting them.

16. Query Shape and EF Core Query Cache

EF Core uses the structure of a LINQ expression to identify queries that can reuse compilation information.

Queries with different expression structures may require separate compilation work.

Example: Different Query Constants

var product1 = await dbContext.Products
    .FirstOrDefaultAsync(p => p.Id == 100);
var product2 = await dbContext.Products
    .FirstOrDefaultAsync(p => p.Id == 200);

For ordinary captured scalar values, EF Core can parameterize values so the query shape can be reused.

A parameterized version is:

var id = 100;
var product = await dbContext.Products
    .FirstOrDefaultAsync(p => p.Id == id);

However, dynamically constructing expression trees with different constant values can result in different query shapes and unnecessary compilation work.

Dynamic Query Construction

When implementing dynamic filtering, prefer parameterized values and reusable expression shapes instead of embedding user-supplied values as constants in dynamically constructed expressions.

Also validate all dynamic field names, sort directions, and filter operators against an allowed list. SQL parameterization protects values, but it does not make arbitrary dynamic SQL identifiers safe.

17. Pagination Optimization

Pagination is used to retrieve a limited number of records at a time.

Offset Pagination

EF Core commonly implements pagination using Skip() and Take().

var products = await dbContext.Products
    .OrderBy(p => p.Id)
    .Skip(1000)
    .Take(20)
    .ToListAsync();

This retrieves 20 products after skipping the first 1,000 rows in the ordered result.

Problem: As the page number increases, the database may need to process many rows before returning the requested page.

Offset Pagination Diagram

Ordered records Rows 1-1000 Skipped Rows 1001-1020 Returned Remaining Not returned The database still has to identify the ordered rows before the requested offset.

Keyset Pagination

Keyset pagination uses the last record from the previous page as the starting point for the next page.

Example:

var products = await dbContext.Products
    .Where(p => p.Id > lastSeenId)
    .OrderBy(p => p.Id)
    .Take(20)
    .ToListAsync();

If the previous page ended at Id 1000, the next page starts with records having Id greater than 1000.

Keyset Pagination Diagram

Ordered records Previous Page Last ID: 1000 Next Page IDs 1001-1020 Remaining Later records Continue from the last seen key instead of skipping a large number of rows.

Keyset Pagination with Multiple Sort Columns

When sorting by multiple columns, the continuation condition must account for all sort columns.

Suppose products are ordered by Price and then Id:

var products = await dbContext.Products
    .Where(p =>
        p.Price > lastPrice
        || (p.Price == lastPrice && p.Id > lastId))
    .OrderBy(p => p.Price)
    .ThenBy(p => p.Id)
    .Take(20)
    .ToListAsync();

The Id provides a unique tie-breaker when multiple products have the same price.

Important: Keyset pagination requires a stable ordering. Use an appropriate index and handle nullable or descending sort columns carefully.

18. Avoid Loading Entire Tables

Loading all records can cause excessive memory usage and database work.

Bad Example

var products = await dbContext.Products
    .ToListAsync();
var activeProducts = products
    .Where(p => p.IsActive)
    .ToList();

This loads every product into application memory and filters afterward.

Better Example

var activeProducts = await dbContext.Products
    .Where(p => p.IsActive)
    .ToListAsync();

The filter is translated into SQL and applied by the database.

For Large Data Processing

Use pagination or streaming when appropriate.

var query = dbContext.Products
    .AsNoTracking()
    .Where(p => p.IsActive)
    .OrderBy(p => p.Id);
await foreach (var product in query
    .AsAsyncEnumerable())
{
    ProcessProduct(product);
}

Streaming avoids creating a full List of all results. However, the database reader and connection remain in use while the stream is being consumed. Keep processing efficient and avoid starting concurrent operations on the same DbContext.

19. Avoid Unnecessary Count Queries

Sometimes developers retrieve records just to check whether any matching record exists.

Bad Example

var products = await dbContext.Products
    .Where(p => p.IsActive)
    .ToListAsync();
bool hasProducts = products.Count > 0;

Better Example

bool hasProducts = await dbContext.Products
    .AnyAsync(p => p.IsActive);

AnyAsync() allows the database to check whether a matching record exists without transferring the entire collection to the application.

Count Only When You Need the Count

int productCount = await dbContext.Products
    .CountAsync(p => p.IsActive);

Use CountAsync() when the actual count is required, not merely to check whether a record exists.

20. Avoid Unnecessary Joins

Including multiple related collections can produce a large joined result set.

Example

var customers = await dbContext.Customers
    .Include(c => c.Orders)
    .Include(c => c.Addresses)
    .ToListAsync();

Suppose a customer has:

  • 10 orders.
  • 5 addresses.

A single query joining both collections can produce up to 50 combinations for that customer before EF Core materializes the related objects.

Cartesian Explosion

1 Customer Parent row 10 Orders First collection 5 Addresses Second collection Joined Result Up to 10 × 5 = 50 combinations Extra Data Transfer and Materialization

This is a simplified illustration of the multiplication caused by joining two collections. Actual row counts depend on the relationships and query structure.

Possible solutions:

  • Use AsSplitQuery().
  • Project only required fields.
  • Load collections separately when appropriate.
  • Avoid including navigation properties that are not needed.

21. Query Filtering and Parameterization

EF Core normally parameterizes values in SQL queries.

Example:

var customerId = 100;
var orders = await dbContext.Orders
    .Where(o => o.CustomerId == customerId)
    .ToListAsync();

Generated SQL may look similar to:

SELECT *
FROM Orders
WHERE CustomerId = @customerId;

Parameterization helps prevent SQL injection for parameterized values and can support plan reuse in SQL Server.

Avoid String-Based SQL Concatenation

Do not construct SQL by directly joining user-supplied values into SQL strings.

Unsafe pattern:

var sql = "SELECT * FROM Products WHERE Name = '"
    + productName + "'";

Use LINQ or parameterized raw SQL instead.

Parameterized Raw SQL Example

var products = await dbContext.Products
    .FromSqlInterpolated(
        $"SELECT * FROM Products WHERE Name = {productName}")
    .ToListAsync();

FromSqlInterpolated() parameterizes interpolated values. Dynamic SQL identifiers, such as table names or column names, still require strict validation because they cannot be passed as ordinary SQL parameters.

22. Avoid Client-Side Evaluation

EF Core translates supported LINQ expressions into SQL.

If a method cannot be translated, EF Core may throw an exception when it appears in a query filter or ordering expression.

Some client-side processing is supported in the top-level projection, but it should be used deliberately.

Example

var products = await dbContext.Products
    .Where(p => CustomBusinessRule(p.Name))
    .ToListAsync();

If CustomBusinessRule() cannot be translated into SQL, this query may fail rather than silently executing the filter in the database.

Better Approach

Where possible, express filtering using operations supported by the database provider.

var products = await dbContext.Products
    .Where(p => p.Name.StartsWith("Laptop"))
    .ToListAsync();

If custom processing is unavoidable, filter and limit the data in SQL first, then perform the remaining processing in application code.

23. EF Core Query Optimization with Aggregations

When you need a count, sum, average, minimum, or maximum, allow the database to perform the calculation.

Bad Example

var orders = await dbContext.Orders
    .ToListAsync();
var totalAmount = orders.Sum(o => o.TotalAmount);

This retrieves all matching orders and calculates the sum in application memory.

Better Example

var totalAmount = await dbContext.Orders
    .SumAsync(o => o.TotalAmount);

The database performs the aggregation and returns a single value.

Grouped Aggregation

var result = await dbContext.Orders
    .GroupBy(o => o.CustomerId)
    .Select(g => new
    {
        CustomerId = g.Key,
        OrderCount = g.Count(),
        TotalAmount = g.Sum(o => o.TotalAmount)
    })
    .ToListAsync();

This is generally more efficient than loading every order and grouping the records in application memory.

24. DbContext Lifetime and Performance

DbContext represents a unit of work and is not thread-safe.

For typical ASP.NET Core applications, register it with a scoped lifetime.

builder.Services.AddDbContext<AppDbContext>(options =>
{
    options.UseSqlServer(
        builder.Configuration.GetConnectionString("Default"));
});

A scoped DbContext is normally created for each request and disposed when the request scope ends.

Do Not Run Concurrent Operations on the Same DbContext

Incorrect:

var productsTask = dbContext.Products.ToListAsync();
var customersTask = dbContext.Customers.ToListAsync();
await Task.WhenAll(productsTask, customersTask);

This attempts to run multiple operations concurrently on one DbContext instance.

EF Core does not support concurrent operations on the same DbContext.

Correct Options

Option 1: Execute sequentially.

var products = await dbContext.Products.ToListAsync();
var customers = await dbContext.Customers.ToListAsync();

Option 2: Use separate DbContext instances for genuinely independent concurrent operations.

public sealed class DashboardService
{
    private readonly IDbContextFactory<AppDbContext> _factory;
    public DashboardService(
        IDbContextFactory<AppDbContext> factory)
    {
        _factory = factory;
    }
    public async Task LoadDashboardAsync()
    {
        await using var productContext =
            await _factory.CreateDbContextAsync();
        await using var customerContext =
            await _factory.CreateDbContextAsync();
        var productsTask = productContext.Products
            .AsNoTracking()
            .ToListAsync();
        var customersTask = customerContext.Customers
            .AsNoTracking()
            .ToListAsync();
        await Task.WhenAll(productsTask, customersTask);
    }
}

Register the factory:

builder.Services.AddDbContextFactory<AppDbContext>(
    options =>
    {
        options.UseSqlServer(
            builder.Configuration.GetConnectionString("Default"));
    });

Use this approach only when concurrent database operations provide a real benefit. More simultaneous queries can also increase database load.

25. Connection Pooling and DbContext Pooling

Connection pooling and DbContext pooling are different optimizations.

Database Connection Pooling

Database providers such as Microsoft.Data.SqlClient generally manage connection pools. Connections are reused rather than creating a new physical database connection for every request.

DbContext Pooling

EF Core supports DbContext pooling to reuse DbContext instances and reduce their initialization overhead.

Example:

builder.Services.AddDbContextPool<AppDbContext>(
    options =>
    {
        options.UseSqlServer(
            builder.Configuration.GetConnectionString("Default"));
    },
    poolSize: 128);

DbContext pooling is useful when context initialization overhead is measurable.

Important considerations:

  • Do not store request-specific state in a pooled DbContext without correctly resetting it.
  • Do not assume pooled contexts are newly constructed for each request.
  • Do not share a context between concurrent operations.
  • Benchmark before enabling pooling.

26. Bulk Operations

EF Core SaveChanges() can send multiple changes to the database using batching, depending on the provider and configuration.

However, updating thousands of entities one by one can still be inefficient.

Traditional Update Approach

var products = await dbContext.Products
    .Where(p => p.IsDiscontinued)
    .ToListAsync();
foreach (var product in products)
{
    product.IsActive = false;
}
await dbContext.SaveChangesAsync();

This loads all matching entities into memory and tracks their changes.

ExecuteUpdateAsync()

EF Core 7 and later support ExecuteUpdateAsync() for suitable bulk updates.

await dbContext.Products
    .Where(p => p.IsDiscontinued)
    .ExecuteUpdateAsync(setters =>
        setters.SetProperty(
            p => p.IsActive,
            false));

This performs the update directly in the database without loading each entity into the change tracker.

ExecuteDeleteAsync()

For bulk deletes:

await dbContext.Products
    .Where(p => p.IsDiscontinued)
    .ExecuteDeleteAsync();

Important: ExecuteUpdateAsync() and ExecuteDeleteAsync() bypass normal entity change tracking. Tracked instances already loaded into the DbContext may become stale. Reload or clear affected tracked state when necessary.

These operations also do not automatically invoke normal entity update behavior such as custom SaveChanges overrides or entity-level change-tracking logic.

27. Raw SQL vs LINQ

EF Core LINQ is suitable for most application queries. Raw SQL can be useful for complex queries or database-specific features that are difficult to express efficiently in LINQ.

LINQ Example

var products = await dbContext.Products
    .Where(p => p.IsActive)
    .OrderBy(p => p.Name)
    .ToListAsync();

Raw SQL Example

var products = await dbContext.Products
    .FromSqlRaw(
        "SELECT * FROM Products WHERE IsActive = {0}",
        true)
    .ToListAsync();

For interpolated values, prefer FromSqlInterpolated() or properly parameterized raw SQL.

Use raw SQL when it provides a measurable advantage or access to required database functionality. It does not automatically perform better than LINQ.

28. Query Performance Measurement

Optimization should be based on measurements rather than assumptions.

Measure the following:

  • Total query execution time.
  • SQL Server CPU time.
  • Logical reads.
  • Physical reads.
  • Number of database round trips.
  • Rows returned.
  • Rows actually read by operators.
  • Memory usage.
  • EF Core materialization overhead.
  • Network latency.

Simple Stopwatch Example

using System.Diagnostics;
var stopwatch = Stopwatch.StartNew();
var products = await dbContext.Products
    .AsNoTracking()
    .Where(p => p.IsActive)
    .ToListAsync();
stopwatch.Stop();
Console.WriteLine(
    $"Query duration: {stopwatch.ElapsedMilliseconds} ms");

This measures the time spent in the application around the entire asynchronous query operation. It is not a pure measurement of SQL Server execution time.

Benchmarking Compiled Queries

When comparing compiled and normal queries:

  1. Use the same database and data.
  2. Use the same query parameters.
  3. Run repeated iterations.
  4. Separate warm-up runs from measured runs.
  5. Measure application-side time and database-side work.
  6. Compare memory allocations as well as elapsed time.
  7. Use a benchmark tool such as BenchmarkDotNet for controlled tests.

29. Query Store in SQL Server

SQL Server Query Store captures query, plan, and runtime information over time.

It can help identify:

  • Frequently executed queries.
  • Queries with high resource consumption.
  • Execution plan changes.
  • Performance regressions.
  • Queries whose performance varies over time.

Query Store is particularly useful when a query was fast previously but became slow after a deployment, schema change, or statistics update.

30. Parameter Sniffing

SQL Server may compile an execution plan using the parameter values available when the query is compiled.

This is commonly called parameter sniffing.

It can be beneficial because the database can select a plan based on actual parameter values. However, a plan that works well for one parameter value may perform poorly for another when data distribution is uneven.

Example

Suppose a query retrieves orders by CustomerId.

SELECT *
FROM Orders
WHERE CustomerId = @CustomerId;

One customer may have 5 orders, while another may have 500,000 orders.

The best execution strategy can differ depending on the parameter value and the data distribution.

When investigating parameter sniffing:

  • Inspect actual execution plans for different parameter values.
  • Compare estimated and actual row counts.
  • Check index design and statistics.
  • Review Query Store plan history.
  • Use SQL Server plan-management or recompilation features only when evidence supports them.

Do not automatically disable parameter sniffing. It is often beneficial and should be investigated before applying workarounds.

31. Common EF Core Performance Mistakes

Mistake Problem Better Approach
Loading all columns Unnecessary data transfer and memory usage. Use Select() projection.
Loading all records Large memory consumption. Use filtering and pagination.
Lazy loading in loops Can create N+1 queries. Use Include() or projection.
Tracking read-only entities Unnecessary tracking overhead. Use AsNoTracking().
Missing indexes Expensive table scans. Analyze execution plans and add suitable indexes.
Functions on indexed columns May prevent efficient index access. Use range predicates where appropriate.
Multiple collection Includes Can create cartesian explosion. Use projection or AsSplitQuery().
Calling ToList() too early Moves later filtering into memory. Keep filtering in IQueryable until needed.
Repeated query execution Executes extra SQL statements. Materialize once when appropriate.
Unnecessary compiled queries Additional code complexity without measurable benefit. Use profiling to identify suitable queries.
Concurrent operations on one DbContext Unsupported concurrent use. Use sequential operations or separate contexts.
Unbounded retries Can increase load during database failures. Use bounded retry policies and timeouts.

32. Complete Optimization Example

Consider an API endpoint that returns active products with category information.

Less Optimized Version

public async Task<IEnumerable<Product>>
    GetProductsAsync()
{
    var products = await _dbContext.Products
        .ToListAsync();
    return products
        .Where(p => p.IsActive)
        .ToList();
}

Problems:

  • Loads all products.
  • Filters after loading data.
  • Loads all entity columns.
  • Tracks entities unnecessarily for a read-only operation.

Optimized Version

public async Task<List<ProductDto>>
    GetProductsAsync(
        int pageNumber,
        int pageSize,
        CancellationToken cancellationToken)
{
    pageNumber = Math.Max(1, pageNumber);
    pageSize = Math.Clamp(pageSize, 1, 100);
    var skip = (pageNumber - 1) * pageSize;
    return await _dbContext.Products
        .AsNoTracking()
        .Where(p => p.IsActive)
        .OrderBy(p => p.Id)
        .Skip(skip)
        .Take(pageSize)
        .Select(p => new ProductDto
        {
            Id = p.Id,
            Name = p.Name,
            Price = p.Price,
            CategoryName = p.Category.Name
        })
        .ToListAsync(cancellationToken);
}

Benefits:

  • Filters records in SQL Server.
  • Loads only the required columns.
  • Does not track read-only entity instances.
  • Retrieves a limited number of records.
  • Projects category information without loading an entire category object graph.
  • Uses asynchronous database operations.

Further optimization: For deep pagination, consider keyset pagination. Inspect the generated SQL and create suitable indexes based on the filtering and ordering columns.

33. Recommended EF Core Optimization Strategy

Follow this order when investigating a slow EF Core endpoint:

  1. Measure the endpoint and identify the slow operation.
  2. Enable EF Core SQL logging in a safe diagnostic environment.
  3. Inspect the generated SQL using ToQueryString() where applicable.
  4. Count the number of database round trips.
  5. Check for N+1 queries.
  6. Inspect the actual SQL Server execution plan.
  7. Review logical reads and estimated versus actual rows.
  8. Check indexes and query predicates.
  9. Remove unnecessary columns and entity materialization.
  10. Use AsNoTracking() for read-only entity queries.
  11. Review joins, Include(), and split-query behavior.
  12. Review pagination and aggregation.
  13. Benchmark compiled queries only if EF Core-side overhead remains significant.
  14. Measure the improvement after each change.

34. Production Best Practices Checklist

  • Use async database operations.
  • Use cancellation tokens in request-driven queries.
  • Use AsNoTracking() for read-only entity queries.
  • Use Select() to retrieve only required columns.
  • Use pagination for large result sets.
  • Use keyset pagination for suitable deep-pagination scenarios.
  • Check for N+1 queries.
  • Avoid unnecessary lazy loading.
  • Use Include() only when the related entities are required.
  • Use AsSplitQuery() when it improves multiple-collection loading.
  • Review SQL Server actual execution plans.
  • Use appropriate indexes.
  • Keep query predicates SARGable where possible.
  • Use compiled queries only after profiling.
  • Use ExecuteUpdateAsync() and ExecuteDeleteAsync() for suitable bulk operations.
  • Do not run concurrent operations on one DbContext.
  • Use DbContext pooling only when it provides a measured benefit.
  • Monitor database CPU, I/O, query duration, and connection usage.
  • Review Query Store for performance regressions.
  • Benchmark important queries using realistic data volumes.

35. Interview Questions and Answers

1. What is EF Core query optimization?

It is the process of improving EF Core query performance by reducing SQL execution cost, database round trips, data transfer, memory usage, and unnecessary application processing.

2. What is an execution plan?

An execution plan describes how the database engine retrieves or modifies data, including scans, seeks, joins, filters, sorts, and other operators.

3. What is the difference between Index Seek and Index Scan?

An Index Seek navigates an index to locate matching entries. An Index Scan reads index entries over a range or across the index. Either can be appropriate depending on selectivity and the amount of data involved.

4. What is the N+1 problem?

It occurs when one query retrieves a parent collection and additional queries retrieve related data separately for each parent record.

5. How do you fix N+1 queries?

Use eager loading with Include(), projection with Select(), suitable joins, or other query designs that retrieve the required data efficiently.

6. What is Include() in EF Core?

Include() loads related navigation data as part of an entity query.

7. What is AsNoTracking()?

It disables normal entity change tracking for query results, making it useful for read-only queries.

8. What is the difference between AsNoTracking() and AsNoTrackingWithIdentityResolution()?

Both avoid normal change tracking. AsNoTrackingWithIdentityResolution() additionally ensures repeated instances of the same entity key are represented by one instance within the query result.

9. What are compiled queries?

Compiled queries are reusable delegates created using EF.CompileQuery() or EF.CompileAsyncQuery() to reduce some EF Core query-processing overhead.

10. Does EF Core already cache queries?

Yes. EF Core automatically caches query compilation information for normal LINQ queries. Explicit compiled queries can further reduce some overhead for suitable high-frequency query shapes.

11. Do compiled queries improve SQL Server execution time?

Not directly. They primarily reduce application-side EF Core query processing overhead. SQL Server still executes the generated SQL.

12. What is projection?

Projection means selecting only the required columns or values, usually using Select().

13. What is a covering index?

A covering index contains the columns needed by a query, potentially allowing the database to retrieve the result without an additional base-table lookup.

14. What is a composite index?

A composite index is an index created on multiple columns. Column order matters and should match important query patterns.

15. What is SARGability?

SARGability describes whether a query predicate can use available indexes efficiently to locate matching rows.

16. What is the difference between AsSplitQuery() and AsSingleQuery()?

AsSingleQuery() loads related data through one SQL query where possible. AsSplitQuery() uses multiple SQL queries to load related collections separately.

17. What is cartesian explosion?

It occurs when joining multiple collection navigations multiplies rows and repeats parent data in the result set.

18. What is keyset pagination?

Keyset pagination retrieves the next page using the last seen sort key rather than skipping an increasing number of rows.

19. What is deferred execution?

Deferred execution means a LINQ query is constructed first and executed when a terminal operation such as ToListAsync() is called.

20. What is ToQueryString()?

ToQueryString() displays the SQL representation of an EF Core query for debugging without executing it.

21. What is parameter sniffing?

Parameter sniffing occurs when SQL Server uses parameter values available during compilation to optimize a query plan. A plan suitable for one parameter value may not be ideal for another.

22. What is ExecuteUpdateAsync()?

ExecuteUpdateAsync() performs a set-based database update without loading and tracking each affected entity.

23. What is the difference between connection pooling and DbContext pooling?

Connection pooling reuses database connections. DbContext pooling reuses EF Core context instances to reduce their initialization overhead.

24. Can one DbContext execute multiple queries concurrently?

No. DbContext is not thread-safe and does not support multiple concurrent operations. Use separate context instances when independent concurrent operations are necessary.

25. How do you identify a slow EF Core query?

Use application profiling, EF Core SQL logging, actual execution plans, SQL Server statistics, and Query Store to identify the source of the performance problem.

36. Final Summary

The most important EF Core optimization techniques are:

Technique Main Benefit
Execution Plan Analysis Identifies expensive database operations.
Index Optimization Improves data retrieval for suitable queries.
Fixing N+1 Reduces unnecessary database round trips.
AsNoTracking() Reduces change-tracking overhead.
Projection Reduces unnecessary data transfer and materialization.
Compiled Queries Reduces some EF Core query-processing overhead.
Keyset Pagination Improves suitable deep-pagination scenarios.
AsSplitQuery() Can reduce cartesian explosion from multiple collection joins.
ExecuteUpdateAsync() Performs bulk updates directly in the database.
Query Store Helps identify slow queries and execution plan regressions.

Most important principle: First identify whether the bottleneck is in EF Core, generated SQL, SQL Server execution, network communication, or result materialization. Optimize the actual bottleneck instead of applying every optimization technique blindly.

37. Official Documentation

🔙
Redis :👈 👉:Database-Transaction-Management