Cookie Consent by Free Privacy Policy Generator Entity Framework (EF) Core Cache - NCache

Entity Framework (EF) Core Cache

100% Native .NET (Industry's Only)

Entity Framework Core (EF Core) is widely used in .NET Core applications for database interactions. However, it has some limitations; high-transaction EF Core applications are likely to experience performance issues at the database tier because of too many database queries. The application tier can be scaled horizontally, but the database tier is a bottleneck.

NCache, a 100% native .NET distributed cache, enhances EF Core applications by caching frequently accessed data and offloading database queries. This improves performance, scalability and reduces the overall load on the database.

Why Use NCache as EF Core Cache?

  • Boost Performance: It reduces database queries, leading to sub-millisecond response times, and caches both transactional and reference data. Includes Client Cache for in-process caching, serving frequently accessed data from the application memory to minimize latency.
  • Linear Scalability: It provides horizontal scaling and ensures consistent performance by supporting multi-server deployment as the application load increases.
  • High Availability: Implements intelligent data replication through Partition-Replica Cache, Mirrored Cache, and Replicated Cache, provides self-healing capabilities, and ensures 100% uptime with a distributed cache cluster.
  • 100% Native .NET: NCache is designed specifically for .NET and EF Core applications; it integrates effortlessly with EF Core extension methods and provides direct EF Core caching APIs.

EF Core Caching thru Extension Methods

NCache extends EF Core with C# extension methods, allowing seamless caching without modifying existing logic.

Caching Transactional Data

Transactional data includes frequently changing records such as customer details, orders, and transactions. Caching this data reduces database queries, speeds up response times, and minimizes contention. (Short-term caching for frequently accessed data).

  • Methods: FromCache(), FromCacheAsync()
    • FromCache(): Retrieves query results from the cache if available; otherwise, fetches from the database and stores the result in the cache for future use.

      Example:

      var customers = context.Customers
                             .Where(c => c.City == "New York")
                             .FromCache(options);

Caching Reference Data

Reference data includes relatively static datasets such as product catalogs and lookup values. Caching this data enhances application speed by eliminating redundant database queries. (Long-term caching for static datasets)

  • Methods: LoadIntoCache(), LoadIntoCacheAsync()
    • LoadIntoCache(): Loads the entire dataset into the cache, ensuring subsequent queries retrieve data directly from the cache instead of the database.

      Example:

      context.Products
             .Where(p => p.InStock == true)
             .LoadIntoCache(out string cacheKey, options);

Querying Cached Reference Data

Retrieving reference data directly from the cache allows applications to avoid database queries, improving response time. However, the entire dataset must be preloaded in the cache to ensure accurate results and avoid incomplete query responses. (Retrieving data directly from cache without database calls).

  • Methods: FromCacheOnly(), FromCacheOnlyAsync()
    • FromCacheOnly(): Retrieves query results exclusively from the cache and does not query the database, ensuring ultra-fast lookups for preloaded datasets.

      Example:

      var discontinuedProducts = context.Products
                                        .Where(p => p.Discontinued == true)
                                        .FromCacheOnly();

Note: Ensure the entire dataset is cached to maintain query accuracy.

Cache Handle for Direct API Access

NCache provides a direct API for managing cached entities efficiently without relying solely on EF Core extension methods. With its caching API, developers can insert, update, and remove objects in the cache programmatically, giving them fine control over caching behavior while optimizing data retrieval for high-performance applications.

  • Insert, Remove, and Update entities directly in cache.
    • Example - Inserting an entity into cache:

      var cache = context.GetCache();
      cache.Insert(new Product { Id = 101, Name = "Laptop" }, out string cacheKey, options);

Advanced Caching Features for EF Core

Deferred Query Execution for Aggregations

Deferred query execution allows applications to perform aggregate functions like Count (), Sum (), and Average () directly on cached data instead of querying the database repeatedly. This reduces redundant queries, improves performance, and speeds up data retrieval in high-transaction environments.

  • Enables caching of aggregated query results like Count (), Sum (), and Average ().
  • Reduces redundant database calls by caching computation results.

    Example:

    int pendingOrders = context.Orders
                               .Where(o => o.Status == "Pending")
                               .DeferredCount()
                               .FromCache(options);

LINQ-to-Cache: Execute LINQ Queries Directly on Cache

NCache allows applications to execute LINQ queries directly on cached data, which eliminates the need for repeated database queries. By leveraging in-memory processing, this approach significantly improves query performance and reduces database load.

  • Run LINQ queries directly on cached data without hitting the database.

    Example:

    var cachedProducts = context.Products
                                .Where(p => p.Category == "Beverages")
                                .FromCacheOnly();

Caching Options: Fine-Tune Your Cache Strategy

NCache provides caching options that allow developers to customize cache behavior based on application requirements. This enables better control over data storage, setting expiration policies, enabling SQL dependency tracking for auto-invalidation, and defining how data is stored in the cache for efficient retrieval.

  • Control cache behavior with absolute & sliding expiration policies.
  • Supports SQL dependency tracking for automatic cache invalidation.

    Example:

    var options = new CachingOptions
    {
        QueryIdentifier = "CustomerData",
        CreateDbDependency = true,
        StoreAs = StoreAs.SeparateEntities
    };
    options.SetAbsoluteExpiration(DateTime.Now.AddMinutes(5));

Built-in Logging & Monitoring

NCache includes built-in logging and monitoring features to track cache usage, measure performance metrics, and detect potential issues in real-time. It integrates seamlessly with Microsoft.Extensions.Logging, which allows developers to analyze cache behavior, troubleshoot problems, and optimize performance efficiently.

  • Provides real-time monitoring of cached EF Core operations.
  • Fully integrates with Microsoft.Extensions.Logging for detailed logs.

Getting Started with NCache

Install NCache Client for EF Core

  • Use NuGet to install the required package:
    Install-Package EntityFrameworkCore.NCache

Install NCache Server

  • Install NCache on two servers to create a distributed caching cluster.
  • Configure a two-node NCache cluster with NCache Management Center

Configure NCache in EF Core

  • Add NCache configuration to DbContext:
    public partial class NorthwindContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string cacheId = "myCache";
            var options = new CacheConnectionOptions { /* options here */ };
            NCacheConfiguration.Configure(cacheId, DependencyType.SqlServer, options);
            optionsBuilder.UseSqlServer("your_connection_string");
        }
    }

What to Do Next?

© Copyright Alachisoft 2002 - 2025. All rights reserved. NCache is a registered trademark of Diyatech Corp.