8 Tips To Improve EF Core Performance
Entity Framework Core EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
These are few tips that can help you to improve performance :
1/ Use projections
Instead of retrieving entire columns from your table, project only the necessary properties you need for your application logic. Same applies to tables, only include necessary tables.
Why would we bring something that we don’t need !
2/ Use async methods
When performing database operations, leverage asynchronous methods (e.g., ToListAsync, FirstOrDefaultAsync) to avoid blocking the main thread while waiting for database responses.
This keeps your application responsive, especially in scenarios with high database load.
3/ Use compiled queries
EF can pre-compile frequently used queries into optimized execution plans. This reduces the overhead of parsing and translating queries at runtime, leading to faster execution.
4/ Avoid non-cancellable queries If your application might need to cancel long-running database operations (e.g., user cancellation), avoid using non-cancellable methods like ToList or ToArray.
Instead, use the cancellable versions ToListAsync(cancellationToken) to allow for graceful termination.
5/ Use database context pool
For applications with high database interaction, consider using a DbContextPool. This pool reuses existing database contexts, reducing the overhead of creating new connections for each operation.
6/ For multiple filters use IQueryable
Build your query incrementally using IQueryable methods like Where, OrderBy, Skip, and Take. This allows EF to optimize the query plan based on all filters at once.
7/ Use AsNoTracking for read only operations
When you only need to read data from the database and don’t intend to modify the retrieved entities, use the AsNoTracking method on your EF query.
This instructs EF to not track the entities in its change tracker. This reduces memory overhead and improves performance, especially for large datasets.
8/ Use pagination, don’t bring all data once
When dealing with extensive datasets, retrieving all data at once can overwhelm your application’s memory and processing capabilities.
Implement pagination to fetch data in smaller chunks (pages) based on user selection (e.g., page number, number of items per page). This improves responsiveness and user experience.
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place