Skip to content

EF Core Query Cache — Complete Guide

DodaTech Updated 2026-06-24 2 min read

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.

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 IMemoryCache or IDistributedCache for 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

  1. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  2. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  3. Using return to 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

What is the difference between first-level and second-level cache?

EF Core's first-level cache is the change tracker — it caches entities by primary key within a DbContext instance. Second-level cache is external (memory, Redis) and shared across DbContext instances. First-level is automatic; second-level requires configuration.

Should I cache IQueryable or materialized results?

Always cache materialized results (ToList, ToArray, First). Caching IQueryable defers execution to the consumer, bypassing the cache. The cache key should include the intended query parameters.

How do I invalidate cached queries when data changes?

Use cache tags: when saving changes to Category, remove all cache entries tagged with "categories". Libraries like EFCoreSecondLevelCacheInterceptor support automatic cache invalidation based on table-level dependencies.

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