EF Core Query Cache — Complete Guide
In this tutorial, you'll learn about EF Core Query Cache. We cover key concepts, practical examples, and best practices.
Every time a user loads the homepage, you query the database for the same product categories or settings. These rarely change but are fetched on every request. Caching the results reduces database load and improves response times.
Wrong
public async Task<List<Category>> GetCategoriesAsync()
{
return await db.Categories.AsNoTracking().ToListAsync();
// Runs on every request — database hit every time
}
Output: Hundreds of identical queries per minute. Database serves the same data repeatedly.
Right
public async Task<List<Category>> GetCategoriesAsync()
{
return await _cache.GetOrCreateAsync("categories", async entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10);
return await db.Categories.AsNoTracking().ToListAsync();
});
}
Output: First request hits the database. Subsequent requests return cached data for 10 minutes.
For EF Core second-level caching, use a library like EFCoreSecondLevelCacheInterceptor:
services.AddEFSecondLevelCache(options =>
options.UseMemoryCacheProvider(CacheExpirationMode.Absolute, TimeSpan.FromMinutes(10)));
services.AddDbContext<AppDbContext>((sp, options) =>
options.UseSqlServer(connectionString)
.AddInterceptors(sp.GetRequiredService<SecondLevelCacheInterceptor>()));
Now all AsNoTracking() queries are cached automatically.
Prevention
- Cache read-only data that changes infrequently (categories, settings, reference data).
- Use
IMemoryCacheorIDistributedCachefor application-level caching. - Use second-level cache libraries for automatic EF Core query caching.
- Set appropriate expiration times — balance freshness vs. performance.
- Invalidate cache entries when data changes (cache-tagging or manual eviction).
- Cache at the service layer, not the DbContext layer.
- Monitor cache hit ratios to verify effectiveness.
Common Mistakes with core query cache
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world EF code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Query caching reduces database load in DodaTech's high-traffic pages. For more EF Core, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro