Try Playground
Show / Hide Table of Contents

Configure EF Core Cache

This section focuses on the configurations required to use the NCache Extension Methods in an Entity Framework application and create an EF Core Cache. This requires serializing entities and specifying NCache-specific configurations your EF applications DbContext.

Note

This feature is also available in NCache Professional.

NCache also 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.

Serializing Entities in EFCore cache

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

[Serializable]
public partial class Customers
{
     // Getters setters
}

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 with SqlServer, DependencyType, and CacheConnectionOptions specifying the Cluster Port, Retry Interval, and Connection Retries for the cache. The configurations CacheId and ConnString have been specified in the App.config file:
  • .NET
  • Legacy API
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 cache with connection retries and security
     var options = new CacheConnectionOptions();
     options.RetryInterval = TimeSpan.FromSeconds(3);
     options.ConnectionRetries = 2;
     options.ServerList = new List<ServerInfo>()
     {
         new ServerInfo("20.200.20.XX", 9800)
     };

     // Configure cache with security
     options.UserCredentials = new Credentials("john_smith", "12345");


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

     optionsBuilder.UseSqlServer(connString);

 }
}
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"];

        // configure cache with SQLServer DependencyType and CacheInitParams

        CacheInitParams initParams = new CacheInitParams();
        initParams.RetryInterval = 3;
        initParams.ConnectionRetries = 2;
        initParams.Port = 7801;

        NCacheConfiguration.Configure(cacheId, DependencyType.SQLServer, initParams);

        optionsBuilder.UseSqlServer(connString);
    }
}

Default Schema Configuration for SQL Dependency

Database dependency queries differ slightly from regular SQL queries. Thus, the 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:

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

    // rest of the entity model code goes here
}

This generated query can be used to configure database dependency.

Configuration Options

The configuration options provided by NCacheConfiguration are:

Member 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, it throws a configuration exception.

DatabaseType DependencyType Enum to inform the cache about the database being used by the Entity Framework. The values are:
  • Other = 0
  • SqlServer = 1
  • Oracle = 2
    This enum deals with data invalidation. If data is updated in the database, NCache removes the cached queries as per the affected entities so that new data can be served from the data source on the next query to prevent the usage of stale data.

    NOTE: Entity Framework Core does not support Oracle, so it should be avoided.
    NOTE: In the case of DependencyType set as Other, database dependency is not created.
    NOTE: In the case of DependencyType set as SqlServer, a SQL service broker must be enabled on the SQL server as data invalidation requires the SQL dependency. SQL dependency also requires the special configuration change to DbContext.

  • InitParams CacheConnectionOptions A class that contains customized parameters to initialize cache with the user-specified configurations.
    IsConfigured bool Specifies whether DbContext has been configured with any overriding options or not.
    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.
    errorEnabled Allows users to determine if they want to throw an exception for FromCache and LoadIntoCache queries.
    bulkInsertChunkSize This divides the bulk of entities into smaller chunks and updates the cache chunk-by-chunk. By default, the bulkInsertChunkSize is 1000.

    Sample Code

    NCache provides a sample application for EF Core on GitHub.

    See Also

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

    In This Article
    • Serializing Entities in EFCore cache
    • Specifying Cache Configurations in DbContext
      • Default Schema Configuration for SQL Dependency
    • Configuration Options
    • Sample Code
    • See Also

    Contact Us

    PHONE

    +1 (214) 764-6933   (US)

    +44 20 7993 8327   (UK)

     
    EMAIL

    sales@alachisoft.com

    support@alachisoft.com

    NCache
    • NCache Enterprise
    • NCache Professional
    • Edition Comparison
    • NCache Architecture
    • Benchmarks
    Download
    Pricing
    Try Playground

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

    • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

    • Contact Us
    •  
    • Sitemap
    •  
    • Terms of Use
    •  
    • Privacy Policy
    © Copyright Alachisoft 2002 - 2025. All rights reserved. NCache is a registered trademark of Diyatech Corp.
    Back to top