| Web API Best Practices :👈 | 👉:Clean Architecture in ASP.NET Core |
Entity Framework Core Performance Optimization: 20 Practical Techniques |
Entity Framework Core Performance Optimization: 20 Practical Techniques
Introduction
Entity Framework Core (EF Core) is an Object-Relational Mapper (ORM) that allows .NET applications to interact with databases using C# objects instead of writing SQL queries for every database operation.
Although EF Core simplifies database development, poorly designed queries and inefficient data-access patterns can negatively affect application performance.
Common performance problems include:
- Loading unnecessary columns and records.
- Executing too many database queries.
- Tracking entities that do not need to be updated.
- Missing database indexes.
- Loading related data inefficiently.
- Creating unnecessary database round trips.
- Using inefficient pagination.
- Not analyzing generated SQL queries.
This article explains 20 practical techniques to improve EF Core performance in production applications.
Table of Contents
- Use AsNoTracking for Read-Only Queries
- Use Projection Instead of Loading Entire Entities
- Apply Filtering at the Database Level
- Use Efficient Pagination
- Create Appropriate Database Indexes
- Avoid the N+1 Query Problem
- Use Eager Loading Carefully
- Use Split Queries When Appropriate
- Use Asynchronous Database Operations
- Reduce Database Round Trips
- Use Compiled Queries
- Use DbContext Pooling
- Use Parameterized Queries
- Use ExecuteUpdate and ExecuteDelete
- Update Only the Required Properties
- Use Streaming for Large Result Sets
- Optimize Relationships and Navigation Properties
- Use Raw SQL When Necessary
- Analyze Generated SQL and Execution Plans
- Understand Database Connection Pooling
- Summary and Recommendations
- Conclusion
1. Use AsNoTracking for Read-Only Queries
What is the problem?
By default, EF Core tracks entities returned from a query. Tracking means EF Core maintains information about retrieved entities so that it can identify changes and persist them when SaveChanges() is called.
However, tracking introduces additional memory and processing overhead. If an application only needs to display data and does not intend to modify it, tracking is usually unnecessary.
Without AsNoTracking
var employees = await context.Employees
.Where(e => e.IsActive)
.ToListAsync();
EF Core tracks every employee returned by this query.
With AsNoTracking
var employees = await context.Employees
.AsNoTracking()
.Where(e => e.IsActive)
.ToListAsync();
EF Core does not track the returned entities.
When should you use it?
- Read-only API endpoints.
- Reporting queries.
- Dashboard data.
- Search results.
- Data retrieval operations where entities will not be updated.
Important consideration
If you need to modify an entity later, you can attach it to the DbContext or retrieve it using a tracking query.
For read-only queries involving related entities, AsNoTrackingWithIdentityResolution() is another option. It performs identity resolution without normal change tracking.
2. Use Projection Instead of Loading Entire Entities
What is the problem?
Sometimes an API needs only a few properties, but the query retrieves the entire entity. This causes unnecessary data to be transferred from the database.
Inefficient approach
var employees = await context.Employees
.ToListAsync();
Suppose the Employee table contains EmployeeId, FirstName, LastName, Email, Address, Salary, DateOfBirth, DepartmentId and CreatedDate.
If the API only needs EmployeeId, FirstName and Email, retrieving all columns is unnecessary.
Recommended approach: Select projection
var employees = await context.Employees
.Select(e => new
{
e.EmployeeId,
e.FirstName,
e.Email
})
.ToListAsync();
EF Core generates SQL that retrieves only the required columns.
Projection using DTO
For API applications, using a Data Transfer Object (DTO) is often preferable.
public class EmployeeDto
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string Email { get; set; }
}
var employees = await context.Employees
.Select(e => new EmployeeDto
{
EmployeeId = e.EmployeeId,
FirstName = e.FirstName,
Email = e.Email
})
.ToListAsync();
Benefits
- Reduces database data transfer.
- Reduces application memory usage.
- Avoids loading unnecessary columns.
- Makes API responses smaller.
- Often improves query performance.
Best practice: Use projection for API responses, dashboards and reporting queries instead of retrieving complete entities unnecessarily.
3. Apply Filtering at the Database Level
What is the problem?
Retrieving all records and filtering them in application memory can create serious performance problems.
Inefficient approach
var employees = await context.Employees
.ToListAsync();
var activeEmployees = employees
.Where(e => e.IsActive)
.ToList();
The first query retrieves every employee from the database. Filtering happens afterward in application memory.
Recommended approach
var activeEmployees = await context.Employees
.Where(e => e.IsActive)
.ToListAsync();
EF Core translates the Where condition into SQL.
SELECT *
FROM Employees
WHERE IsActive = 1;
Why is this better?
- The database filters records before returning them.
- Less data travels over the network.
- Application memory consumption is reduced.
- The database can use appropriate indexes.
Best practice: Apply Where, OrderBy, Skip and Take before materializing the query with ToListAsync().
4. Use Efficient Pagination
What is the problem?
Returning thousands of records in a single API response increases database processing, network traffic, application memory usage and API response time.
Pagination allows the application to retrieve a limited number of records at a time.
Offset pagination using Skip and Take
int pageNumber = 1;
int pageSize = 20;
var employees = await context.Employees
.OrderBy(e => e.EmployeeId)
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize)
.ToListAsync();
Conceptually, SQL Server generates a query similar to:
SELECT *
FROM Employees
ORDER BY EmployeeId
OFFSET 0 ROWS
FETCH NEXT 20 ROWS ONLY;
Limitation of offset pagination
When users navigate to very high page numbers, the database may need to process and skip a large number of rows. This can become inefficient for large datasets.
Keyset pagination
Keyset pagination uses the last retrieved record as the starting point for the next page.
int lastEmployeeId = 100;
int pageSize = 20;
var employees = await context.Employees
.Where(e => e.EmployeeId > lastEmployeeId)
.OrderBy(e => e.EmployeeId)
.Take(pageSize)
.ToListAsync();
The next request can use the last EmployeeId returned by the previous request.
Comparison
| Approach | Suitable scenario |
|---|---|
| Skip and Take | Small and medium datasets, page-number navigation. |
| Keyset pagination | Large datasets, infinite scrolling and sequential navigation. |
Best practice: Always use deterministic ordering when implementing pagination. For keyset pagination, use an indexed and stable ordering key.
5. Create Appropriate Database Indexes
What is an index?
A database index is a data structure that helps the database locate records without scanning the entire table.
Without a suitable index, the database may perform a table scan when filtering or sorting records.
Example
var employees = await context.Employees
.Where(e => e.DepartmentId == 10)
.ToListAsync();
If the Employees table contains millions of records, an index on DepartmentId may improve query performance.
Creating an index using Fluent API
protected override void OnModelCreating(
ModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>()
.HasIndex(e => e.DepartmentId);
}
Composite index
Suppose the application frequently executes:
var employees = await context.Employees
.Where(e => e.DepartmentId == 10
&& e.IsActive)
.ToListAsync();
A composite index may help:
modelBuilder.Entity<Employee>()
.HasIndex(e => new
{
e.DepartmentId,
e.IsActive
});
Important considerations
- Index frequently filtered columns.
- Index frequently joined columns where appropriate.
- Consider indexes on frequently sorted columns.
- Use unique indexes for values such as email addresses when uniqueness is required.
- Consider composite indexes for common query combinations.
Too many indexes can reduce INSERT, UPDATE and DELETE performance because indexes also need to be maintained.
Best practice: Create indexes based on actual query patterns and execution-plan analysis, not simply on every database column.
6. Avoid the N+1 Query Problem
What is the N+1 problem?
The N+1 problem occurs when an application executes one query to retrieve a collection of records and then executes one additional query for each record to retrieve related data.
For example, retrieving 100 departments and then loading employees separately for every department may result in 101 database queries.
Inefficient example
var departments = await context.Departments
.ToListAsync();
foreach (var department in departments)
{
var employees = await context.Employees
.Where(e => e.DepartmentId == department.DepartmentId)
.ToListAsync();
}
If there are 100 departments, this code executes approximately 101 queries.
Recommended approach: Eager loading
var departments = await context.Departments
.Include(d => d.Employees)
.ToListAsync();
This retrieves departments and their employees using a query that joins the related data.
Alternative: Projection
var departments = await context.Departments
.Select(d => new
{
d.DepartmentId,
d.DepartmentName,
Employees = d.Employees.Select(e => new
{
e.EmployeeId,
e.FirstName
}).ToList()
})
.ToListAsync();
Benefits
- Reduces unnecessary database round trips.
- Avoids repeated queries.
- Improves API response time.
- Makes database access more predictable.
Best practice: Be careful with lazy loading because accessing navigation properties can trigger additional database queries.
7. Use Eager Loading Carefully
What is eager loading?
Eager loading retrieves related entities as part of the initial query using Include() and ThenInclude().
Example
Consider the following relationships:
- Department has many Employees.
- Employee has many Projects.
var departments = await context.Departments
.Include(d => d.Employees)
.ThenInclude(e => e.Projects)
.ToListAsync();
This retrieves departments, employees and projects together.
Potential performance problem
Including multiple collection navigation properties can produce a large SQL result set because of JOIN operations.
For example:
var departments = await context.Departments
.Include(d => d.Employees)
.Include(d => d.Projects)
.ToListAsync();
If one department has 10 employees and 5 projects, the joined result may contain repeated department information across many rows. This is known as cartesian explosion.
Better approach
Use only the relationships actually required by the application. For read-only API responses, consider projection:
var departments = await context.Departments
.Select(d => new
{
d.DepartmentId,
d.DepartmentName,
EmployeeCount = d.Employees.Count()
})
.ToListAsync();
Best practices
- Avoid unnecessary Include() statements.
- Use projection for API responses.
- Avoid loading large object graphs without a clear requirement.
- Consider split queries when multiple collections are involved.
8. Use Split Queries When Appropriate
What is a split query?
By default, EF Core may retrieve related collections using a single SQL query with multiple JOIN operations. For complex object graphs, this can produce a large number of repeated rows.
Split queries retrieve related collections through separate SQL queries instead.
Single-query approach
var departments = await context.Departments
.Include(d => d.Employees)
.Include(d => d.Projects)
.ToListAsync();
Split-query approach
var departments = await context.Departments
.Include(d => d.Employees)
.Include(d => d.Projects)
.AsSplitQuery()
.ToListAsync();
Advantages
- Reduces cartesian explosion.
- Can reduce duplicated data transferred from the database.
- Can improve performance for complex collection relationships.
Disadvantages
- Executes multiple database queries.
- Requires additional database round trips.
- Data may change between individual queries unless an appropriate transaction or isolation level is used.
Best practice: Compare both approaches using actual SQL execution plans and application performance measurements.
9. Use Asynchronous Database Operations
What is the problem?
Database operations can take time because the application needs to communicate with an external database server. Synchronous database calls block the current thread while waiting for the database response.
Synchronous approach
public List<Employee> GetEmployees()
{
return context.Employees.ToList();
}
Asynchronous approach
public async Task<List<Employee>> GetEmployeesAsync()
{
return await context.Employees.ToListAsync();
}
Benefits
- Frees the request thread while waiting for I/O.
- Improves scalability under concurrent requests.
- Helps web applications handle more simultaneous operations.
- Supports responsive application design.
Asynchronous operations do not automatically make an individual SQL query execute faster. They improve how the application handles waiting for I/O.
Also, do not execute multiple parallel operations on the same DbContext instance. DbContext is not thread-safe.
Common asynchronous methods
| Synchronous method | Asynchronous method |
|---|---|
| ToList() | ToListAsync() |
| FirstOrDefault() | FirstOrDefaultAsync() |
| SingleOrDefault() | SingleOrDefaultAsync() |
| Any() | AnyAsync() |
| Count() | CountAsync() |
| SaveChanges() | SaveChangesAsync() |
Best practice: Use asynchronous EF Core methods in ASP.NET Core applications, especially for database operations in request-processing workflows.
10. Reduce Database Round Trips
What is a database round trip?
A database round trip occurs when an application sends a request to the database and waits for the response. Each round trip introduces network communication and database processing overhead.
Inefficient approach
foreach (var employeeId in employeeIds)
{
var employee = await context.Employees
.FirstOrDefaultAsync(e => e.EmployeeId == employeeId);
}
If employeeIds contains 100 IDs, this code may execute 100 separate queries.
Recommended approach
var employees = await context.Employees
.Where(e => employeeIds.Contains(e.EmployeeId))
.ToListAsync();
EF Core translates the collection condition into an appropriate database query, such as an IN condition for SQL Server.
Other ways to reduce round trips
- Retrieve related data using appropriate eager loading.
- Use projection to retrieve the required data.
- Use ExecuteUpdateAsync() for bulk updates.
- Use ExecuteDeleteAsync() for bulk deletes.
- Avoid executing queries inside loops.
- Batch database operations where supported and appropriate.
Best practice: Reduce unnecessary round trips while keeping SQL queries efficient and manageable.
11. Use Compiled Queries for Frequently Executed Queries
What is a compiled query?
EF Core normally processes LINQ queries and translates them into SQL. EF Core internally caches query compilation results, but query processing still involves some overhead.
Compiled queries allow an application to explicitly compile a frequently executed query and reuse it.
Example
private static readonly Func<AppDbContext, int, Employee?>
GetEmployeeById =
EF.CompileQuery(
(AppDbContext context, int id) =>
context.Employees
.FirstOrDefault(e => e.EmployeeId == id));
Usage:
var employee = GetEmployeeById(context, 100);
Asynchronous compiled query
private static readonly Func<AppDbContext, int,
IAsyncEnumerable<Employee>> GetEmployees =
EF.CompileAsyncQuery(
(AppDbContext context, int departmentId) =>
context.Employees
.Where(e => e.DepartmentId == departmentId));
Usage:
await foreach (var employee in GetEmployees(context, 10))
{
Console.WriteLine(employee.FirstName);
}
Benefits
- Reduces repeated query-compilation overhead.
- Useful for frequently executed, stable query shapes.
- Can improve performance in high-throughput applications.
Best practice: Consider compiled queries only after identifying query-compilation overhead as a meaningful performance concern.
12. Use DbContext Pooling
What is DbContext pooling?
Creating a DbContext instance has some overhead. EF Core provides DbContext pooling to reuse context instances instead of repeatedly creating and disposing them.
Normal registration
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")));
Pooled registration
builder.Services.AddDbContextPool<AppDbContext>(
options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")));
How does it work?
EF Core maintains a pool of reusable DbContext instances. When an application finishes using a pooled context, EF Core resets its internal state and makes it available for reuse.
Benefits
- Reduces DbContext initialization overhead.
- Reduces allocation pressure.
- Can improve performance in high-throughput applications.
Important considerations
- DbContext pooling is different from database connection pooling.
- Do not store request-specific state in a pooled DbContext without correctly managing its lifecycle.
- EF Core resets its own managed state, but application-managed state may require additional care.
- Configure pooling based on actual application requirements.
13. Use Parameterized Queries
What is the problem?
Building SQL queries by directly concatenating user input can create SQL injection vulnerabilities. It can also interfere with efficient query-plan reuse.
Unsafe approach
string sql =
"SELECT * FROM Employees WHERE Email = '"
+ email + "'";
var employees = await context.Employees
.FromSqlRaw(sql)
.ToListAsync();
This is unsafe because user input is inserted directly into the SQL statement.
Recommended approach using LINQ
var employee = await context.Employees
.FirstOrDefaultAsync(e => e.Email == email);
EF Core automatically parameterizes the value.
Parameterized raw SQL
var employees = await context.Employees
.FromSqlInterpolated(
$"SELECT * FROM Employees WHERE Email = {email}")
.ToListAsync();
Benefits
- Helps prevent SQL injection.
- Allows database query plans to be reused where supported.
- Separates SQL structure from parameter values.
FromSqlRaw() is not inherently unsafe. It becomes dangerous when untrusted input is concatenated directly into the SQL string.
Use parameters for values. SQL identifiers such as table names and column names generally cannot be supplied as ordinary SQL parameters, so dynamic identifiers must be validated against an allowlist.
Best practice: Prefer LINQ or parameterized SQL for database operations involving user input.
14. Use ExecuteUpdate and ExecuteDelete
What is the problem?
Traditionally, updating multiple records using EF Core involves loading entities, modifying them and calling SaveChanges(). This creates unnecessary object materialization and change-tracking overhead when the operation does not require individual entity processing.
Traditional approach
var employees = await context.Employees
.Where(e => e.IsActive == false)
.ToListAsync();
foreach (var employee in employees)
{
employee.IsActive = true;
}
await context.SaveChangesAsync();
This loads all matching employees into application memory.
Recommended approach: ExecuteUpdateAsync()
await context.Employees
.Where(e => e.IsActive == false)
.ExecuteUpdateAsync(setters =>
setters.SetProperty(
e => e.IsActive,
true));
EF Core translates this into a database-level UPDATE statement.
ExecuteDeleteAsync()
await context.Employees
.Where(e => e.IsActive == false)
.ExecuteDeleteAsync();
Instead of loading records before deleting them, EF Core executes a database-level DELETE operation.
Benefits
- Avoids loading matching entities into memory.
- Avoids normal change-tracking overhead.
- Reduces database communication.
- Performs bulk operations efficiently.
Important considerations
- ExecuteUpdateAsync() and ExecuteDeleteAsync() are available in EF Core 7 and later.
- These operations execute directly against the database.
- They do not update already tracked entity instances in the current DbContext.
- They do not automatically invoke the normal SaveChanges() pipeline or its SaveChanges interceptors.
- Database constraints and triggers still apply.
15. Update Only the Required Properties
What is the problem?
Sometimes an application retrieves an entire entity only to update one property. This introduces unnecessary database reads and change-tracking work.
Inefficient approach
var employee = await context.Employees
.FirstOrDefaultAsync(e => e.EmployeeId == 100);
employee.IsActive = false;
await context.SaveChangesAsync();
This requires a SELECT operation followed by an UPDATE operation.
Alternative: Attach and mark a property as modified
var employee = new Employee
{
EmployeeId = 100,
IsActive = false
};
context.Employees.Attach(employee);
context.Entry(employee)
.Property(e => e.IsActive)
.IsModified = true;
await context.SaveChangesAsync();
EF Core can generate an UPDATE statement for the specified property without first retrieving the complete record.
Another option: ExecuteUpdateAsync()
await context.Employees
.Where(e => e.EmployeeId == 100)
.ExecuteUpdateAsync(setters =>
setters.SetProperty(
e => e.IsActive,
false));
Important considerations
- Ensure the entity key is correct.
- Be careful not to overwrite properties unintentionally.
- Consider concurrency tokens when concurrent updates are possible.
- Choose ExecuteUpdateAsync() when a direct database update is more appropriate.
16. Use Streaming for Large Result Sets
What is the problem?
ToListAsync() loads the complete query result into application memory. This can become expensive when retrieving hundreds of thousands or millions of records.
Loading all records
var employees = await context.Employees
.ToListAsync();
All matching employees are materialized into memory.
Streaming using AsAsyncEnumerable()
await foreach (var employee in context.Employees
.AsNoTracking()
.AsAsyncEnumerable())
{
Console.WriteLine(employee.FirstName);
}
Records are processed as they are read from the database rather than first collecting the complete result in a list.
Benefits
- Reduces application memory usage.
- Useful for large exports.
- Useful for processing large datasets.
- Avoids materializing the entire result set at once.
Important considerations
- The database connection remains in use while enumeration is active.
- Process records promptly.
- Avoid starting another operation on the same DbContext while enumeration is in progress.
- Use pagination when the application needs independent pages or resumable processing.
17. Optimize Relationships and Navigation Properties
What is the problem?
Entity relationships make EF Core convenient, but inefficient navigation-property access can result in unnecessary database queries.
Consider the following relationship:
- Department has many Employees.
- Employee belongs to one Department.
Entity example
public class Department
{
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
public ICollection<Employee> Employees { get; set; }
}
public class Employee
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public int DepartmentId { get; set; }
public Department Department { get; set; }
}
Inefficient approach
When lazy loading is enabled, accessing a navigation property can trigger another database query.
var employees = await context.Employees
.ToListAsync();
foreach (var employee in employees)
{
Console.WriteLine(
employee.Department.DepartmentName);
}
This may produce additional queries for department information.
Recommended approach: Explicit projection
var employees = await context.Employees
.Select(e => new
{
e.EmployeeId,
e.FirstName,
DepartmentName = e.Department.DepartmentName
})
.ToListAsync();
Best practices
- Understand one-to-one, one-to-many and many-to-many relationships.
- Avoid unnecessary navigation-property traversal.
- Use projection when only related values are needed.
- Use Include() when complete related entities are genuinely required.
- Avoid enabling lazy loading without understanding its query behavior.
18. Use Raw SQL When Necessary
What is raw SQL?
EF Core supports executing SQL statements directly when LINQ does not provide a convenient or efficient way to express a particular database operation.
Example using FromSqlInterpolated()
var employees = await context.Employees
.FromSqlInterpolated(
$"SELECT * FROM Employees WHERE IsActive = 1")
.ToListAsync();
Example using Database.SqlQuery
For supported EF Core versions and database providers, Database.SqlQuery can execute SQL that returns scalar or unmapped result types.
var employeeNames = await context.Database
.SqlQuery<string>(
$"SELECT FirstName FROM Employees")
.ToListAsync();
When should you use raw SQL?
- Complex database-specific queries.
- Specialized SQL features.
- Queries that are difficult to express using LINQ.
- Carefully measured performance-critical operations.
- Stored procedures where appropriate.
Important considerations
- Raw SQL is not automatically faster than LINQ.
- Parameterize all user-supplied values.
- Avoid unnecessary database-provider dependencies.
- Ensure the SQL is maintainable and tested.
- Understand whether the query returns tracked or untracked entities.
Best practice: Prefer LINQ for normal data-access operations. Use raw SQL when it provides a clear benefit that justifies the additional maintenance responsibility.
19. Analyze Generated SQL and Execution Plans
Why is this important?
EF Core translates LINQ expressions into SQL queries. A LINQ query that looks simple in C# may generate inefficient SQL.
Therefore, developers should understand the SQL generated by EF Core.
View generated SQL using ToQueryString()
var query = context.Employees
.Where(e => e.IsActive)
.OrderBy(e => e.FirstName);
string sql = query.ToQueryString();
Console.WriteLine(sql);
ToQueryString() helps inspect the SQL generated for an IQueryable query.
Enable EF Core logging
builder.Services.AddDbContext<AppDbContext>(
options =>
options.UseSqlServer(connectionString)
.LogTo(Console.WriteLine,
LogLevel.Information));
For production applications, configure logging carefully. Avoid exposing sensitive data or logging excessive SQL information.
Analyze execution plans
An execution plan shows how the database executes a SQL query.
For SQL Server, useful tools include:
- Actual Execution Plan.
- Estimated Execution Plan.
- SQL Server Management Studio.
- Query Store.
- Database performance monitoring tools.
What should you look for?
| Item | What it indicates |
|---|---|
| Table Scan | The database may be reading many rows. |
| Index Seek | The database is locating matching rows through an index. |
| Index Scan | The database is scanning an index. |
| Key Lookup | Additional lookups may be required to retrieve columns. |
| Expensive Sort | Sorting may be consuming significant resources. |
| High logical reads | The query may be reading too much data. |
| Long execution time | The query or database operation may need investigation. |
Best practices
- Inspect generated SQL for important queries.
- Review execution plans for slow queries.
- Check whether indexes are being used effectively.
- Measure logical reads and execution time.
- Avoid optimizing based only on how the LINQ code looks.
Best practice: Optimize the SQL execution behavior, not just the C# code that generates it.
20. Understand Database Connection Pooling
What is connection pooling?
Opening a physical database connection can be an expensive operation. Database providers such as Microsoft.Data.SqlClient maintain connection pools so that physical connections can be reused.
When an application opens a connection, the provider can provide an available connection from the pool. When the application closes or disposes the connection, it is normally returned to the pool.
Example
await using var connection =
new SqlConnection(connectionString);
await connection.OpenAsync();
// Execute database operations.
Disposing the connection returns it to the connection pool when pooling is enabled.
Benefits
- Reduces the overhead of creating physical connections.
- Improves database connection reuse.
- Helps applications handle concurrent database operations.
- Reduces connection-establishment overhead.
Connection pooling vs DbContext pooling
| Feature | Connection Pooling | DbContext Pooling |
|---|---|---|
| Managed by | Database provider | EF Core |
| Reuses | Database connections | DbContext instances |
| Main purpose | Reduce connection creation overhead | Reduce DbContext initialization overhead |
| Configuration | Connection string/provider settings | AddDbContextPool() |
| Scope | Database connection lifecycle | DbContext lifecycle |
Important considerations
- Always dispose database connections properly.
- Avoid holding connections open longer than necessary.
- Configure connection pool limits based on workload.
- Monitor connection exhaustion.
- Remember that DbContext pooling does not replace connection pooling.
Summary and Recommendations
All 20 techniques at a glance
| No. | Technique | Main benefit |
|---|---|---|
| 1 | AsNoTracking | Reduces tracking overhead. |
| 2 | Projection | Retrieves only required columns. |
| 3 | Database-level filtering | Reduces unnecessary data retrieval. |
| 4 | Efficient pagination | Limits records returned. |
| 5 | Database indexes | Improves data lookup. |
| 6 | Avoid N+1 queries | Reduces unnecessary database queries. |
| 7 | Careful eager loading | Controls related-data retrieval. |
| 8 | Split queries | Helps avoid cartesian explosion. |
| 9 | Async operations | Improves application scalability. |
| 10 | Reduce round trips | Reduces communication overhead. |
| 11 | Compiled queries | Reduces repeated query-compilation overhead. |
| 12 | DbContext pooling | Reduces context initialization overhead. |
| 13 | Parameterized queries | Improves security and supports query-plan reuse. |
| 14 | ExecuteUpdate/Delete | Efficient bulk operations. |
| 15 | Partial entity updates | Updates only required properties. |
| 16 | Streaming | Reduces memory usage for large results. |
| 17 | Relationship optimization | Avoids unnecessary related-data loading. |
| 18 | Raw SQL | Supports specialized database operations. |
| 19 | SQL and execution-plan analysis | Identifies actual database bottlenecks. |
| 20 | Connection pooling | Reuses database connections. |
Which techniques should you prioritize?
High priority
- Use AsNoTracking for read-only queries.
- Use projection instead of loading complete entities.
- Apply filtering and pagination at the database level.
- Create appropriate database indexes.
- Avoid N+1 queries.
- Review generated SQL and execution plans.
Medium priority
- Use eager loading and split queries appropriately.
- Use asynchronous database operations.
- Reduce unnecessary database round trips.
- Use ExecuteUpdateAsync() and ExecuteDeleteAsync() for bulk operations.
Advanced optimization
- Consider compiled queries.
- Consider DbContext pooling.
- Use streaming for large datasets.
- Consider raw SQL for specialized operations.
- Tune connection pooling based on workload.
Important performance principle
Do not apply every optimization blindly.
- AsNoTracking is useful for read-only queries, but not when you expect normal change tracking.
- Split queries can reduce large JOIN results, but they introduce additional round trips.
- Indexes improve some reads, but can increase write costs.
- Compiled queries can reduce query-processing overhead, but cannot fix an inefficient execution plan.
- Raw SQL may help with specialized queries, but it is not automatically faster than LINQ.
Always measure performance before and after making changes.
Conclusion
Entity Framework Core provides many features for building efficient data-access layers, but application performance depends on how these features are used.
The most important optimization techniques are:
- Retrieve only the data required by the application.
- Avoid unnecessary change tracking.
- Apply filtering and pagination in the database.
- Use indexes based on actual query patterns.
- Prevent N+1 queries.
- Reduce unnecessary database round trips.
- Use asynchronous operations for database I/O.
- Analyze generated SQL and database execution plans.
- Measure performance before introducing advanced optimizations.
A production-ready application should focus on efficient SQL execution, controlled memory usage, appropriate database access patterns and reliable performance monitoring.
| Web API Best Practices :👈 | 👉:Clean Architecture in ASP.NET Core |