Sobes.tech
Middle

How is caching implemented in Entity Framework Core?

sobes.tech AI

Answer from AI

Entity Framework Core (EF Core) has two-level caching:

  1. Context Cache (Identity Resolution): This is the first-level cache. EF Core tracks entities loaded into the current DbContext. If EF Core finds an entity with the same key value in the context's memory during a query, it returns the existing instance instead of querying the database.

    • Prevents loading the same data multiple times within a single context.
    • Automatically updates in-memory instances when their state changes (add, modify, delete).
    • Works by default and does not require special configuration.
  2. Query Cache (Query Caching): This is the second-level cache. EF Core caches execution plans of generated SQL queries. When the same query is executed again, EF Core can reuse the already compiled plan, avoiding re-compilation of SQL.

    • Optimizes performance of repeated queries with the same structure (but different parameters).
    • Caches not the query result (the data itself), but its execution plan.
    • Managed by EF Core's internal mechanisms and not directly accessible for external configuration or clearing.

Example of context cache operation:

// assuming a User with Id == 1 exists in the database
using (var context = new AppDbContext())
{
    // First load - database query
    var user1 = context.Users.FirstOrDefault(u => u.Id == 1);
    Console.WriteLine($"User1 loaded: {user1.Name}");

    // Second load - object is retrieved from the context cache
    var user2 = context.Users.FirstOrDefault(u => u.Id == 1);
    Console.WriteLine($"User2 loaded: {user2.Name}");

    // user1 and user2 are references to the same object in memory
    Console.WriteLine($"Are user1 and user2 the same object reference? {ReferenceEquals(user1, user2)}");
}

It is important to understand that EF Core does not provide built-in application-wide data caching (e.g., for storing frequently used data between requests or users). For such scenarios, external solutions like Redis, IMemoryCache, or other distributed caches are typically used.