• Facebook
  • Twitter
  • Youtube
  • LinkedIn
  • RSS
  • Docs
  • Comparisons
  • Blogs
  • Try NCache
  • Contact Us
Try NCache
Show / Hide Table of Contents

Entity Framework (EF) Core Installation and Configuration

This page provides a guide on integrating NCache with Entity Framework (EF) Core as a Second-Level Cache (L2 Cache). By caching database results in NCache’s distributed cache memory, you can eliminate database latency and boost application performance. The required packages, namespaces, and configuration steps needed to use NCache as an EF Core caching provider are detailed below.

Prerequisites

  • .NET
  • Install the following NuGet packages in your EF Core Client application:
    • NCache: EntityFrameworkCore.NCache
    • NCache Open Source: EntityFrameworkCore.NCache.OpenSource
  • Include the following namespaces in your application:
    • Alachisoft.NCache.EntityFrameworkCore
    • Alachisoft.NCache.Client
    • Alachisoft.NCache.Runtime.Caching
  • The cache must be running.
  • Make sure that the data being added is serializable.
  • For API details, refer to: ServerInfo, SecurityOptions, CreateWithCredentials, BulkInsertChunkSize, CacheId, NCacheConfiguration, Configure, and DependencyType.

Configure EF Core Cache

Integrating NCache as a second-level cache for EF Core enhances application scalability by shifting query results to a distributed cache. Three main steps are required: designating entities as [Serializable], setting up the NCacheConfiguration in your DbContext's OnConfiguring method, and choosing to enable SQL Server Service Broker for automated data invalidation. NCache provides users with the flexibility to synchronize the cache if items are invalidated due to Expiration or Eviction. This keeps the data fresh in the cache and reduces network trips to the database to fetch the expired items.

Step 1: Marking EF Core Entities for Cache Serialization

Before configuring an EF Core Cache, all entities in any database model need to be serialized for storage in NCache; therefore, they have to be marked as serializable.

  • .NET
[Serializable]
public partial class Customers
{
    // Getters and setters
}

Step 2: Specifying Cache Configurations in DbContext

NCache provides configurable cache properties specified in the DbContext to configure EF Core Cache. The NCacheConfiguration class allows users to specify the properties and configure the logger for your application:

Important

You must configure NCache in the DbContext or as a point of entry for the application, otherwise, it will throw an exception stating that the NCache initialization configuration has not been provided.

The following code sample configures NCache for the EF application in an extended DbContext class. It specifies the database dependency type, cache server endpoint, and security credentials through the provider's Configure overload. This overload accepts CacheConnectionOptions, so use that type when passing initialization parameters to the EF Core provider.

Note

When using the NCache 5.3.800 SDK, client retry counts, retry intervals, timeouts, Keep Alive, and load balancing are configured on the cache server under <client-settings><connection-options>. These settings are supplied to clients after they connect. Assigning the corresponding deprecated properties on CacheConnectionOptions does not override the server configuration. For example, to use two connection retries with a three-second retry interval, set connection-retries="2" and retry-interval="3" in that server-side section for the target cache. These settings apply to clients connecting to that cache, including the EF Core provider.

  • .NET
public partial class NorthwindContext : DbContext
{
...
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
   {
    // Parameters specified in App.config
    string cacheId = ConfigurationManager.AppSettings["CacheId"];
    string connString = ConfigurationManager.AppSettings["ConnString"];
    bool errorEnabled = bool.Parse(ConfigurationManager.AppSettings["ErrorEnabled"]);
    int bulkInsertChunkSize = Int32.Parse(ConfigurationManager.AppSettings["BulkInsertChunkSize"]);

    // Configure the server endpoint used by the EF Core provider
    var options = new CacheConnectionOptions();
    options.ServerList = new List<ServerInfo>()
    {
        new ServerInfo("20.200.20.11", 9800)
    };

    // Configure cache with security
    options.Security = SecurityOptions.CreateWithCredentials("john_smith", "<password>");


    NCacheConfiguration.Configure(cacheId, DependencyType.SqlServer, options, errorEnabled, bulkInsertChunkSize);

    optionsBuilder.UseSqlServer(connString);
   }
}
Note

To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.

Step 3: Enabling SQL Dependency and Schema Mapping

Database dependency queries differ slightly from regular SQL queries. Thus, SQL Server does not accept these queries as valid. To avoid this issue, the dbo needs to be appended before the table name where the default schema is set as dbo. This can be done by adding the following line of code in the OnModelCreating method in the DbContext class:

  • .NET
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.HasDefaultSchema("dbo"); // add this line for SQL dependency

    // rest of the entity model code goes here
}

This configuration allows NCache to generate database dependency queries with the required schema.

Configuration Options

The configuration options provided by NCacheConfiguration are:

Member / Parameter Type Description
CacheId string Specifies the name of the cache to use for serving in the Entity Framework application. If no cache name is specified, a configuration exception is thrown.
DatabaseType DependencyType Specifies the type of database being used by the Entity Framework application. The values are: Other = 0, SqlServer = 1, and Oracle = 2. This setting is used for data invalidation. When data is updated in the database, NCache removes the affected cached query results so that fresh data can be retrieved from the data source. If DependencyType is set to Other, database dependency is not created. If it is set to SqlServer, SQL Server Service Broker must be enabled because data invalidation requires SQL dependency.
InitParams CacheConnectionOptions Supplies application-specific connection information, such as server endpoints and security credentials, to the EF Core provider. With the NCache 5.3.800 SDK, deprecated retry, timeout, load-balancing, and client logging properties do not override the server-side client settings.
IsConfigured bool Specifies whether the NCache EF Core provider has been configured.
errorEnabled bool Specifies whether exceptions are thrown for errors that occur while executing FromCache and LoadIntoCache queries.
bulkInsertChunkSize int Specifies the number of entities processed in each chunk during bulk cache insertion. The entities are divided into smaller chunks and inserted into the cache chunk by chunk. The default value is 1000.
Method Description
Configure Configures the cache to be used for serving in the Entity Framework application. This sets the configuration of the cache according to the user-specified properties. It takes in the cache ID, database dependency type, and any optional initialization parameters for the cache.
ConfigureLogger Configures instance(s) of Microsoft.Extensions.Logging.ILogger via a Microsoft.Extensions.Logging.ILoggerFactory to log details of operations from the caching provider.
IsLoggerEnabled Specifies if the logger has been enabled at the specified log level or not.
Note

Configure NCache client logging on the cache server under <client-settings><logging>. The EF Core provider's ConfigureLogger method controls its own diagnostic logging; see EF Core Provider Logging.

Sample Code

NCache provides a sample application for EF Core on GitHub.

See Also

.NET: Alachisoft.NCache.EntityFrameworkCore and Alachisoft.NCache.Runtime.Caching namespaces.

Contact Us

PHONE

+1 214-619-2601   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • Edition Comparison
  • NCache Architecture
  • Benchmarks
Try NCache
Pricing
NCache Playground

Deployments
  • Cloud
  • Docker
  • Kubernetes
  • On-Premises
Technical Use Cases
  • ASP.NET Sessions
  • ASP.NET Core Sessions
  • Pub/Sub Messaging
  • SignalR Backplane
  • Internet of Things (IoT)
  • NoSQL Database
  • Stream Processing
  • Microservices
Resources
  • Blogs
  • Foundations
  • Videos
  • Comparisons
  • Shows
  • Whitepapers
  • Articles
  • Tech Talks
  • Magazine Articles
  • Third-Party Articles
Customer Case Studies
  • Testimonials
  • Customers
Support
  • Docs
  • Schedule a Demo
  • Tips
Company
  • Leadership
  • Partners
  • News
  • Events
  • Careers
Contact Us

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Terms of Use
  •  
  • Privacy Policy
  •  
  • Cookie Policy
© Copyright Alachisoft 2002 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.
  • Facebook
  • Twitter
  • Youtube
  • LinkedIn
  • RSS