EF Core performance techniques at a glance
On trails:EFCOREstep 8/8
| Technique | Description | When to use, and the benefit | Key snippet |
|---|---|---|---|
| DbContext pooling | Reuses DbContext instances to reduce initialization overhead. |
High-throughput applications, for example ASP.NET Core, that create many DbContext instances. Reduces allocation and setup cost. |
services.AddDbContextPool<MyContext>(...) |
| Compiled queries | Pre-compiles LINQ queries into .NET delegates, bypassing runtime compilation and cache lookup. | For very frequently executed (“hot path”) queries where profiling shows the compilation overhead is significant. | EF.CompileAsyncQuery((MyContext ctx, int id) => ctx.Entities.Where(e => e.Id == id)) |
AsNoTracking() |
Disables change tracking for queried entities. | Read-only scenarios where entities won’t be updated. Reduces memory and processing overhead. | context.Entities.AsNoTracking().ToListAsync() |
| Eager loading | Loads related data as part of the initial query, using Include() and ThenInclude(). |
When related data is always needed, to avoid N+1 queries. | context.Blogs.Include(b => b.Posts).ToList() |
| Query splitting | Generates separate SQL queries for included collections, to avoid cartesian explosion. | Queries that load multiple related collections, where a single query becomes inefficient. | context.Blogs.Include(b => b.Posts).AsSplitQuery().ToList() |
| Global query filters | Defines LINQ predicates that are applied automatically to all queries for an entity type. | Implementing soft deletes, multi-tenancy, or other consistent filtering rules. | modelBuilder.Entity<Post>().HasQueryFilter(p => !p.IsDeleted); |
| Select projections | Retrieves only the specific columns or properties needed, not entire entities. | When only a subset of the entity data is required. Reduces data transfer and materialization cost. | context.Entities.Select(e => new { e.Id, e.Name }).ToList() |
Each one is explained in the query habits noteEF Core query habitsSix habits that keep EF Core queries fast.Opens in a new tab, the pooling and compiled queries notePooling, compiled queries and compiled modelsFour ways to cut overhead in EF Core, and two common mix-ups between them.Opens in a new tab and the loading noteLoading related dataEager, explicit and lazy loading, and the N+1 problem that lazy loading can cause.Opens in a new tab.
Sources
- Advanced Performance Topics, EF Core, Microsoft Learn · accessed May 16, 2025