Best practices for using EF Core Second Level Cache Interceptor
masterTo use the interceptor effectively, follow these guidelines:
- Selection Criteria: Cache global site settings, public data (e.g., articles, comments), or user-specific data that changes infrequently. Avoid caching small, frequently changing per-user data; use alternatives like user claims in cookies instead.
- User Scoping: The cache is application-scoped, not user-scoped. It does not use session variables. To cache per-user data safely, you must include a user ID filter in your query, such as
.Where(x => x.UserId == id). - Invalidation: The cache automatically updates when entities are inserted, updated, or deleted via a
DbContextusing this interceptor. Note that modifications made outside the interceptor (e.g., stored procedures, triggers, or other applications) will result in stale cache data. - Transactions: By default, queries inside an explicit transaction (
context.Database.BeginTransaction()) are not cached. However, CRUD operations within that transaction will still trigger cache invalidation. To enable caching within transactions, use.AllowCachingWithExplicitTransactions(true). - Database Compatibility: If your database provider lacks support for types like
DateTimeOffsetorTimeSpan, you must configure EF Core [value converters] in yourDbContextto handle these types.