DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • From Naked Objects to Naked Functions
  • Strategies for Improving the Performance of Applications Using EF Core
  • Build a Full Stack App With SvelteKit and OceanBase
  • Providing Enum Consistency Between Application and Data

Trending

  • Comparing SaaS vs. PaaS for Kafka and Flink Data Streaming
  • Scalability 101: How to Build, Measure, and Improve It
  • Stateless vs Stateful Stream Processing With Kafka Streams and Apache Flink
  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  1. DZone
  2. Coding
  3. Frameworks
  4. How to Configure Entity Framework Caching

How to Configure Entity Framework Caching

Let's see how to configure entity framework caching.

By 
Iqbal Khan user avatar
Iqbal Khan
·
Updated May. 08, 20 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
59.6K Views

Join the DZone community and get the full member experience.

Join For Free

Distributed Caching With Entity Framework

The Entity Framework is a set of technologies in ADO.NET that support the development of data-oriented software applications. With the Entity Framework, developers can work at a higher level of abstraction when they deal with data and can create and maintain data-oriented applications with less code than in traditional applications.

NCache introduces the caching provider, which acts between Entity Framework and the Data source. The major reason behind the EF Caching provider is to reduce database trips (which slow down application performance) and serve the query result from the cache. The provider acts in between the ADO.NET entity framework and the original data source. Therefore, the caching provider can be plugged without changing/compiling the current code.

You may also like: Entity Framework (EF) Core Cache

Integration Modes

NCache Entity Framework Caching provider works under two modes. It can either be in "Caching" or in "Analysis" mode. In caching mode, you can cache the result-set of selected queries. Analysis mode works in pass-through mode and helps you find the queries that you should cache by generating a report showing which queries are being called with what frequency.

Database Synchronization

NCache Entity Framework provider also ensures that data in the cache is always synchronized with the database. Therefore, NCache uses .NET SqlCacheDependeny, which registers a SQL query with SQL Server so if any row in the dataset represented by this query is changed in the database, SQL Server throws an event notification to NCache. NCache then removes the corresponding result-set from the cache.

How to Integrate NCache With Entity Framework

Prerequisites

1. You should have an Entity Framework application. (You can also use sample application for EFCaching from NCache sample applications from the following path:
"Installeddirectory:/ProgramFiles/NCache/samples/clr20/EntityDataModelIntegrationDemo")

In every Entity Framework application, ADO.NET Entity Data Model is already added, which automatically generates two files:

  • SSDL
  • Application (or web) configuration file

2. Microsoft Visual Studio 2010 for Entity Framework 3.5 and 4.0 and Microsoft Visual Studio 2012/2013 for Entity Framework 6.0 and 6.1

3. Database Tool (e.g. MS SQL SERVER 2008, ORACLE)

Steps to Enable NCache Caching

Step 1: Add Reference

Add Alachisoft.Integrations.EntityFramework.CachingProvider reference to your Entity Framework application. This .dll file is placed on the following path:
"Installeddirectory:/ProgramFiles/NCache/integration/MSEntityFramework"
After adding the reference, changes are required in 3 different files.

Step 2: SSDL Configurations (for Entity Framework 3.5 and 4.0)

In SSDL file, which is generated on adding ADO.NET Entity Data Model in Entity Framework application, the following changes are required:

Below are the sample changes for an SQL 2008 database.

In SSDL, the provider name is specified in the Provider attribute of the <Schema/> element as shown below:

[Existing Code]

Java
 




xxxxxxxxxx
1


 
1
<Schema Namespace = "NorthwindModel.Store" Alias = "Self" Provider = "System.Data.SqlClient" ProviderManifestToken = "2005" 
2
xmlns:store ="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" 
3
xmlns ="http://schemas.microsoft.com/ado/2006/04/edm/ssdl">


In order to inject our NCache Entity Framework Provider, we need to override the above-highlighted attributes to plugin our provider. In SSDL, we put the name of the new provider in the Provider attribute and concatenate the previous provider with our provider manifest token in the ProviderManifestToken field, as shown below:

[Changed Code]

Java
 




xxxxxxxxxx
1


 
1
<Schema Namespace = "NorthwindModel.Store" Alias = "Self" 
2
Provider = "Alachisoft.Integrations.EntityFramework.CachingProvider"
3
ProviderManifestToken = "System.Data.SqlClient;2005" 
4
xmlns:store = "http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" 
5
xmlns = "http://schemas.microsoft.com/ado/2006/04/edm/ssdl">


Step 3: Application (or Web) Configurations

Application (or web) configuration file, which is generated on adding ADO.NET Entity Data Model in Entity Framework application, requires the following changes:

Entity Framework 3.5 and 4.0

  • Provider invariant name is specified in the connection string of application or web configuration file:
    Java
     




    xxxxxxxxxx
    1
    11


     
    1
    <connectionStrings>
    2
        <add name="NorthwindEntities" 
    3
        connectionString="metadata=res://*/NorthwindCustomerModel.csdl
    4
        |res://*/NorthwindCustomerModel.ssdl
    5
        |res://*/NorthwindCustomerModel.msl;
    6
        provider=System.Data.EntityClient;
    7
        provider connection string="
    8
        Data Source=localhost;Initial Catalog=Northwind;user id= userid;
    9
        password=password;MultipleActiveResultSets=True"" 
    10
        providerName="System.Data.EntityClient"/>
    11
    </connectionStrings>


  • Change provider name to NCache Entity Framework Provider and also add the provider wrapper information in the connection string as shown below:
    Java
     




    xxxxxxxxxx
    1
    12


     
    1
    <connectionStrings>
    2
        <add name="NorthwindEntities" 
    3
        connectionString="metadata=res://*/NorthwindCustomerModel.csdl
    4
        |res://*/NorthwindCustomerModel.ssdl
    5
        |res://*/NorthwindCustomerModel.msl;
    6
        provider=Alachisoft.Integrations.EntityFramework.CachingProvider;
    7
        provider connection string="
    8
        wrappedProvider=System.Data.SqlClient;        
    9
        Data Source=localhost;Initial Catalog=Northwind;user id= userid;
    10
        password=password;MultipleActiveResultSets=True"" 
    11
        providerName="System.Data.EntityClient"/>
    12
    </connectionStrings>


  • Also add the provider factory for the initialization of NCache Entity Framework Provider. The invariant attribute should be the same as the provider name in the connection string.
  • Java
     




    xxxxxxxxxx
    1
    13


     
    1
    <DbProviderFactories>
    2
        <add name="EF Caching Data Provider" 
    3
        invariant="Alachisoft.Integrations.EntityFramework.
    4
        CachingProvider" 
    5
        description="Caching Provider Wrapper" 
    6
        type="Alachisoft.NCache.Integrations.
    7
        EntityFramework.EFCachingProviderFactory, 
    8
        Alachisoft.Integrations.EntityFramework.
    9
        CachingProvider, 
    10
        Version=1.0.0.0,
    11
        Culture=neutral,
    12
        PublicKeyToken=cff5926ed6a53769"/>
    13
    </DbProviderFactories>


Entity Framework 6.0

  • Provider invariant name is also specified in the application (or web) configuration file:
    XML
     




    xxxxxxxxxx
    1


     
    1
    <entityFramework>
    2
        <providers>
    3
    <provider invariantName="System.Data.SqlClient"
    4
          type="System.Data.Entity.SqlServer.SqlProviderServices,
    5
           EntityFramework.SqlServer" />
    6
        </providers>
    7
    </entityFramework>


  • Change invariant name to EFCachingProviderServices and type to Alachisoft.NCache.Integrations.EntityFramework.EFCachingProviderServices, 
    Alachisoft.Integrations.EntityFramework.CachingProvider as shown below:
  • XML
     




    xxxxxxxxxx
    1


     
    1
    <entityFramework>
    2
        <providers>
    3
            <provider invariantName="EFCachingProviderServices" 
    4
            type="Alachisoft.NCache.Integrations.EntityFramework.EFCachingProviderServices,
    5
             Alachisoft.Integrations.EntityFramework.CachingProvider" />
    6
        </providers>
    7
    </entityFramework>


    Entity Framework 6.1

  • Add an interceptor in provider section in the application (or web) configuration file:
    XML
     




    xxxxxxxxxx
    1
    11


     
    1
    <entityFramework>
    2
        <providers>
    3
            <provider invariantName="System.Data.SqlClient"
    4
             type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    5
        </providers>
    6
    
                
    7
        <interceptors>
    8
    <interceptor type="Alachisoft.NCache.Integrations.EntityFramework.Caching.EFCommandInterceptor,
    9
             Alachisoft.Integrations.EntityFramework.CachingProvider" />
    10
        </interceptors>
    11
    </entityFramework>


  • The following information should be added in appSettings of app.config/web.config:
    Java
     




    xxxxxxxxxx
    1


     
    1
    
                
    2
    <appSettings> <add key = "app-id" value = "PersonNameApp2"/> <add key = "logging-level" value = "Debug"/> </appSettings>


    1. App-id: This will be the identifier for the current application. This ID will be used to read configurations from efcaching.ncconf
    2. Logging-level: Determine the logging level for the application. Our provider will log exceptions and errors only when the level is set to Error. When the level is set to Debug, both exceptions/errors and other detailed information will be logged. Nothing will be logged if the level is set to Off (default). Path at which log files will be generated: Default =<install-dir> <install-dir>/log-files/efcaching-logs/
    3. For applying the above changes, the application should be restarted after these changes are made

NOTE: App-id for efcaching.ncconf should be same as in application (app.config) otherwise it will prompt an error)

Alternative Method

Entity Framework 3.5 or 4.0

Apart from specifying the connection string in app.config/web.config, the connection can also be specified while creating ObjectContext or EntityConnection. While creating a connection string programmatically, the wrapper information must be included in a connection string. Here is how the connection string can be created and ObjectContext or EntityConnection can be initialized.

Java
 




xxxxxxxxxx
1
17


 
1
  try
2
    {
3
        SqlConnectionStringBuilder sqlConnBuilder =     new SqlConnectionStringBuilder();
4
        sqlConnBuilder.DataSource = "localhost";
5
        sqlConnBuilder.InitialCatalog = "EFTestDB";
6
        sqlConnBuilder.IntegratedSecurity = true;
7
        string conString = sqlConnBuilder.ToString();
8
        EntityConnectionStringBuilder efConnBuilder = new EntityConnectionStringBuilder();
9
        efConnBuilder.Provider = "EFCachingProvider";
10
        efConnBuilder.ProviderConnectionString = @"wrappedProvider=System.Data.SqlClient;" + conString;
11
        efConnBuilder.Metadata = "res:// /NorthwindCustomerModel.csdl|res:" + "// /NorthwindCustomerModel.ssdl|res:" +"// /NorthwindCustomerModel.msl;";
12
        EntityConnection connection = new EntityConnection(efConnBuilder.ToString());
13
    }
14
    catch (Exception ex)
15
    { 
16
        // handle exception
17
    }


Entity Framework 6.0

Apart from specifying provider invariant in app.config/web.config, the provider invariant can be specified while initializing the configuration (class inheriting DbConfiguration). Here is how the provider invariant can be specified:

Java
 




xxxxxxxxxx
1


 
1
    try
2
    {
3
        this.SetProviderServices("EFCachingProviderServices", EFCachingProviderServices.Instance);
4
    }
5
    catch (Exception ex)
6
    { 
7
        // handle exception
8
    }


Entity Framework 6.1

Apart from specifying database interceptor in app.config/web.config, the database interceptor can be specified while initializing the configuration (class inheriting DbConfiguration). Here is how the interceptor can be specified:

Java
 




xxxxxxxxxx
1


 
1
    try
2
    {
3
        this.AddInterceptor(new EFCommandInterceptor());
4
    }
5
    catch (Exception ex)
6
    { 
7
        // handle exception
8
    }


Through API (6.0 and 6.1)

The user can now also cache results using an extension provided for IQueryable.

  • Specify the namespace
  • Java
     




    xxxxxxxxxx
    1


     
    1
     using Alachisoft.NCache.Integrations.EntityFramework.Caching;


  • Call cache method overloads now from IQueryable instance
Java
 




xxxxxxxxxx
1


 
1
 var students = from s in db.Students
2
             select s;
3
students.Cache(); 
4
// results are not cached yet
5
foreach (Student student in students) 
6
//results are cached when enumerator from query is iterated completely
7
{
8
  //using student
9
}


Step 4: efcaching.ncconf Configurations

Changes required in "efcaching.ncconf".

  1. Efcaching.ncconf is placed on the following path: "Installeddirectory:/Program Files/NCache/config".
  2. Provider Configuration contains cache and caching policy-related information. Below are the changes required in efcaching.ncconf.
    Java
     




    xxxxxxxxxx
    1


     
    1
    <configuration>
    2
          <app-config app-id = "PersonNameApp" mode = "analysis|caching">


  3. "Analysis" mode is used for monitoring the number of times each query executes and then it generates a report. The report contains the Query text and the call count for each query. This report can be used in Custom policy. No caching is done at this mode.
    Java
     




    xxxxxxxxxx
    1


     
    1
    <analysis-policy log-path = "" analysis-time = "1min" cache-enable-threshold = "1" default-expiration-type = "Sliding" default-expiration-time = "180sec" dbsyncdependency= "false"/>


  4. Log-path: Path at which analysis log files will be generated. Default = < install-dir > /log-files/efcaching-analysis-logs/
  5. For "Caching" mode, the wrapping provider will cache the results of all the specified queries. Both policies have their own specifications. Whenever an update is detected (either UPDATE, INSERT or DELETE) in a respective database, the provider invalidates affected cache entries by evicting all cached queries which were dependent on any of the updated tables.
    Java
     




    xxxxxxxxxx
    1


     
    1
    <cache-policy-configuration database = "none|sqlserver|oracle" cache-id = "mycache">


  6. For custom policy, it includes user-configurable list of queries that should be cached with their results. Only those query results will be cached for which the caching is enabled. You can specify custom caching policy for all queries.
    Java
     




    xxxxxxxxxx
    1


     
    1
    <!--sql-query = "SELECT [Extent1].[CustomerID] AS [CustomerID],= @param_0"-->
    2
    <query>
    3
            <cache-query query text="SELECT [Extent1].[OrderID] AS [OrderID], < @param_0"/>
    4
                <cache-policy vary-by-cache-param="param_0" expiration-type="Sliding"
    5
                 enabled="True" expiration-time="180sec" dbsyncdependency="False"/>
    6
    </query>


  7. In case of stored procedures, query text will be the name of a stored procedure, and there will be no default policy or database sync dependency. User can cache stored procedures result with expiration only, no database dependency is required here.
  8.  In case of API Level Caching (supported in Entity Framework 6.0 and 6.1), you can cache query using extension method provided in the namespaceusing Alachisoft.NCache.Integrations.EntityFramework.Caching;
    and you can provide caching policy for API level caching in configuration file in the following tag:
    Java
     




    xxxxxxxxxx
    1


     
    1
    <api-level-caching expiration-type="sliding|absolute" enable="True|False"
    2
     expiration-time="120sec" dbsyncdependency="True|False">


Database Entity Framework Cache (computing) Framework application

Published at DZone with permission of Iqbal Khan. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • From Naked Objects to Naked Functions
  • Strategies for Improving the Performance of Applications Using EF Core
  • Build a Full Stack App With SvelteKit and OceanBase
  • Providing Enum Consistency Between Application and Data

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!