Cookie Consent by Free Privacy Policy Generator Entity Framework Second Level Cache with NCache

Entity Framework Second Level Cache with NCache

Entity Framework is a tried and tested Microsoft object-relational mapping framework for .NET. It enables you to work with relational data through domain objects. And, it eliminates the need for most of the database persistence code that you would otherwise need to write.

Entity Framework is used in high-transaction applications where performance and scalability are critical. But, in most of these applications, the database quickly becomes a bottleneck. As, unlike the application tier, where you can add more application servers as you need to scale, you cannot do the same with the database tier.

The only way to achieve this scalability is with distributed cache like NCache. It is an extremely fast and scalable distributed cache for .NET applications. It lets you cache application data, reduce expensive database trips, and improves your application performance and scalability.

Entity Framework Second Level Cache (L2 Cache) is a caching pattern that preserves data across different database contexts and user sessions. While Entity Framework 6.x (Classic) does not provide this natively, NCache plugs in as a custom ADO.NET provider. This allows you to offload queries to a distributed cluster, ensuring linear scalability and 100% uptime without changing your code.

Why Use NCache as Entity Framework Second-level Cache?

If your Entity Framework application is running in a multi-server environment, then you need a distributed cache as an Entity Framework Second Level Cache. And, NCache is an ideal option for multi-server configurations, and you should use it for the following reasons:

  1. NCache is extremely fast: NCache gives you sub-millisecond response times.
  2. NCache provides linear scalability: NCache never becomes a scalability bottleneck. It lets you add servers to the cache cluster to achieve linear scalability and handle extreme transaction loads.
  3. Cache size can grow infinitely: NCache provides cache partitioning and pools all the cache server memory together. So, you can increase the cache size by simply adding more servers to the cluster.
  4. NCache replicates data intelligently: NCache lets you intelligently replicate the cache without compromising performance. So, you won't lose any cache data even if a cache server goes down.
  5. NCache gives you 100% uptime: NCache has a self-healing dynamic cache cluster with no single point of failure. As a result, it allows you to add or remove cache servers at runtime without stopping your application or the cache.

Ideal Scenarios for EF L2 Caching:

  • Reference Data: Caching static lookup tables (e.g., Products, Countries) to eliminate redundant SQL reads.
  • High-Traffic Read Operations: Reducing database load for catalog or listing pages.
  • Session-Agnostic Data: Sharing state across multiple web servers where standard InProc caching fails.

How to Configure NCache as Entity Framework Second-level Cache (No Code Required)

The best thing about using NCache with Entity Framework is that there is no programming required on your part. You simply modify your application's configuration files by adding an interceptor in the <provider> section and overwriting the invariantName and type configurations. Here is an example of app.config changes:

<entityFramework>
    <providers>
        <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
    <interceptors>
        <interceptor type="Alachisoft.NCache.Integrations.EntityFramework.Caching.EFCommandInterceptor, Alachisoft.Integrations.EntityFramework.CachingProvider"/>
    </interceptors>
</entityFramework>

Use Analysis Mode and Caching Mode

The NCache Entity Framework Second-level Cache provider plugs in as a custom ADO.NET provider. This provider allows you to run in analysis mode, where it logs all the different queries your application issues to Entity Framework. These queries are logged in a file along with a count of how many times this query was called during this analysis mode. Below is an example:

<analysis-report>
 <query>
      <!--Call count = 12-->
      <cache-query query-text="SELECT [Extent1].[ProductID] AS [ProductID], 
		[Extent1].[ProductName] AS [ProductName], 
		[Extent1].[SupplierID] AS [SupplierID], 
		[Extent1].[CategoryID] AS [CategoryID], 
		[Extent1].[QuantityPerUnit] AS [QuantityPerUnit], 
		[Extent1].[UnitPrice] AS [UnitPrice], 
		[Extent1].[UnitsInStock] AS [UnitsInStock], 
		[Extent1].[UnitsOnOrder] AS [UnitsOnOrder], 
		[Extent1].[ReorderLevel] AS [ReorderLevel], 
		[Extent1].[Discontinued] AS [Discontinued] FROM 
		[dbo].[Products] AS [Extent1] 
		WHERE 5 = [Extent1].[ProductID]"/>
      <cache-policy vary-by-cache-param="" 
		expiration-type="Absolute" 
		enabled="True" 
		expiration-time="30sec" 
		dbsyncdependency="False" 
		resyncProviderName="EFResync"/>
    </query>
</analysis-report>

This allows you to determine which queries you want to cache and for how long. You can also specify database synchronization for some or all of your queries.

NCache Features for Entity Framework Second-level Cache

By plugging in NCache Entity Framework Second-level Cache provider through app.config changes, you are going to gain an enterprise-level distributed cache for your application. Following are some features NCache provides for Entity Framework apps.

  1. Synchronize cache with database: Some data that is in the cache may change in the database without your application's knowledge. For such data, you can specify the corresponding classes for the NCache database synchronization feature.  This allows NCache to then connect with the database, monitor data changes, and then update the cache automatically. This ensures that data in the cache is always synchronized with the database. NCache provides SqlDependency for SQL Server, OracleDependency for Oracle, and DbDependency for any OLEDB-compliant databases.
  2. Absolute Expiration: Absolute expiration in NCache is specified separately for each cached item. It employs a date-time value to determine when NCache automatically invalidates the item. For Entity Framework, NCache asks you to specify an "interval" value and then uses "Now() + interval" formula to calculate the date-time value for absolute expiration.
  3. Sliding Expiration: Sliding expiration in NCache is specified separately for each cached item and is an interval value. NCache expires the cached item if it has neither been fetched nor updated for this interval. You can specify this interval through the NCache Entity Framework Second Level Cache provider configuration file.
  4. Compact Serialization: Whenever any .NET object is cached in an out-of-process or distributed cache, it must first be serialized. Regular .NET serialization is slow because it uses .NET Reflection at runtime. NCache provides a way for you to register your classes with NCache, and it generates serialization code when your application connects to the cache. It then compiles this code in memory and uses it for serialization. This is almost 10 times faster than regular .NET serialization. You can use this feature with Entity Framework, by registering your entity classes with NCache for Compact Serialization.

Using NCache Directly from Entity Framework Applications

Although, using NCache as Entity Framework Second Level Cache is very quick and easy, it only provides you with a limited set of NCache features. The reason for this is that NCache is bound by the fact that it is plugged in as a custom ADO.NET provider and must deal at the SQL query level. There are numerous NCache features that you are unable to use if you decide to use it as a Entity Framework Second-level Cache Provider.

The alternative for you is to use NCache directly from within your Entity Framework application by making NCache API calls like all other non-Entity Framework .NET applications do. Although, there is a small programming effort to take this path, you might decide that the benefits outweigh the extra programming effort.

NCache Features Missed in Entity Framework Second-level Cache

Below is a list of features you would miss if you used it as Entity Framework Second Level Cache versus if you used NCache directly from your application.

Feature Category Feature EF Caching Provider (No Code) NCache Direct API
Advanced Operations Bulk Operations Not Available Available
Grouping & Search Tags and Named Tags Not Available Available
Querying SQL and LINQ Search Not Available Available
Concurrency Locking and Unlocking Items Not Available Available
Integrity Cache Item Versioning Not Available Available
Data Source Read-through / Write-through / Write-behind Not Available Available
Messaging Event Notifications (Item, General, Custom) Not Available Available
Maintenance Cache Loader & Refresher Not Available Available

What to Do Next?

Frequently Asked Questions (FAQ)

NCache implements a custom ADO.NET provider that wraps the standard Entity Framework provider. It intercepts database queries generated by EF and caches their result sets in the distributed cache. If the same query is executed again, the result is served directly from the cache, bypassing the database.

No, using NCache as an Entity Framework Second Level Cache requires zero code changes. You only need to modify your app.config or web.config file to register the NCache provider and configure the interceptor.

Yes. NCache supports database synchronization using SqlDependency (for SQL Server), OracleDependency, and DbDependency. This ensures that if data is updated in the database by a third-party application, the corresponding cache items are automatically invalidated to prevent stale data.

No, this specific provider is designed for Entity Framework 6.x (Classic). For .NET Core applications, please use the NCache Entity Framework Core (EF Core) Caching Provider, which supports advanced features like Extension Methods and custom caching options.

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