Entity Framework Cache. How to Optimize Your Code

Facebook
Twitter
LinkedIn

Never miss a post!

Sign up for our newsletter and get FREE Development Trends delivered directly to your inbox.

You can unsubscribe any time. Terms & Conditions.
Categories

Entity Framework acts like a connector between an application and data sources. It has a wide variety of libraries to access data and support the developers to focus on the services rather than working with the database. The major reason behind using caching is to avoid the multiple round trips to the database. Review our tips of how to improve the performance your application and serve the queries faster by fetching the results from cache instead of  the database.

How to use Entity Framework Redis Cache

A cache is mainly used to speed up the performance of an application by reducing the need of accessing data layer for every call of data. In every application, there is a tradeoff between space and time as per the requirement of a program. A cache usually stores the data from any data source in memory of an application or any computing environment unlike database whose data is typically more complete and robust.

Entity Framework provides robust way of programming a database application to access and store data into the database. It also helps in loading data into cache from the database and fetching records from the cache on the subsequent data requests. Redis is also known as Remote Dictionary Server, is an open source distributed caching in an application. It supports various data structures such as lists, hashes, bitmaps, strings, etc.

Redis Cache Configuration Steps in .NET Application

  • You need to create C# project in .NET application
  • Add Entity Framework library through NuGet Manager or run the command ‘Install-Package EntityFramework’ in the Package Manger Console
  • Add reference of the assembly of Redis Entity Framework and connection string in app.config file of an application. Your app.config file will look similar to the below one:
<configuration>
...
<connectionstrings>
<add name="RedisContext" connectionstring="Offline=False;Server=127.0.0.1;Port=ABC123;Password=myPassword;" providername="System.Data.CData.Redis"></add>
</connectionstrings>
<entityframework>
<providers>
...
<provider invariantname="System.Data.CData.Redis" type="System.Data.CData.Redis.RedisProviderServices, System.Data.CData.Redis.Entities.EF6"></provider>
</providers>
<entityframework>
</entityframework></entityframework></configuration>
  • Add a reference to System.Data.CData.Redis.Entities.EF6.dll
  • Build the project to ensure that everything is running smoothly before moving towards the actual implementation of caching technique
  • Add a DatabaseContext class to the project and override the onModelCreating function in the class
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration.Conventions;
 
class RedisAppContext : DbContext {
    public RedisAppContext () { }
 
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // To remove the requests to the Migration History table
        Database.SetInitializer(null); 
        // To remove the plural names   
        modelBuilder.Conventions.Remove();
    } 
}
  • Add another class for the Redis Entity that needs to be store into a cache
using System.Data.Entity.ModelConfiguration;
using System.ComponentModel.DataAnnotations.Schema;
 
[System.ComponentModel.DataAnnotations.Schema.Table("Products")]
public class Products 
{
    [System.ComponentModel.DataAnnotations.Key]
    public System.String ProductCode { get; set; }
    public System.String ProductDescription { get; set; }
}
  • Add the above entity to the context class
public DbSet Products { set; get; }
  • After creating the entity and context classes, you can use it in any class to query any dataset from database
RedisAppContext context = new RedisAppContext();
context.Configuration.UseDatabaseNullSemantics = true;
var query = from line in context.Products select line;

NCache vs Entity Framework Cache

 In .NET applications, NCache is a scalable distributed cache that provides extremely fast results by quering data from a cache result sets. It helps you to store extensive data, thus reduces the round trips of database and improves the performance of an application. The popularity of Entity Framework in high-level transactional application is increased a lot but this can cause the bottlenecks in an application because you cannot add more database servers unlike application tier in which more application servers can be added. Entity Framework does not support the model of Second Level Cache. By using NCache, it helps in caching the result sets of the queries of Entity Framework. It provides two models for the caching. It can be either Caching Mode or Analysis Mode. Entity Framework cannot work in both modes simultaneously. You need to choose the mode as per the requirement of your application.

 Caching Mode

Caching mode is designed for caching the result sets of queries in .NET applications. It stores the data of those queries at the time of execution, which are listed in the configuration file “efcaching.ncconf” of an application. This file contains the cache and its related policies used by the provider of NCache Entity Framework.

<configuration>
    <app-config app-id="EFAppCacheDemo" mode="analysis|caching">
    <analysis-policy log-path="" analysis-time="1min" cache-enable-threshold="1" 
                     default-expiration-type="Sliding" 
                     default-expiration-time="150sec" 
                     dbsyncdependency="false"/>
    <cache-policy-configuration database="none|sqlserver|oracle" cache-id="mycache">
    <!--sql-query = "SELECT [Extent1].[EmployeeID] AS [EmployeeID],= @param_0"-->
    <query>
          <cache-query querytext="SELECT [Extent1].[CustomerID] AS [CustomerID], &lt; @param_0"/>
          <cache-policy vary-by-cache-param="param_0" expiration-type="Sliding" 
                        enabled="True" 
                        expiration-time="150sec" 
                        dbsyncdependency="False">
     </query>
     </cache-policy-configuration>
     </app-config>
</configuration>

Analysis Mode

 Analysis Mode does not store result instantly and no caching is performed at the time of fetching the results. It helps in monitoring the frequency of the query that is executed each time. This mode allows you to choose the most frequent queries to be copied into a cache. It also generates reports and list all the requested queries in descending order to be set for caching.

<analysis-report>
    <!--Call-count = 34-->
    <query query-text="" ["select * from Customers"] |
    [stored-procedure-name = ""]
    caching = "true"
    expiration-type="absolute" |
    sliding = ""
    expiration-time="150"
    dbsyncdependency = "true"/>
</analysis-report>

Final Thoughts

A caching technique stores the data in a memory for rapid access. It fastens the performance of an application by reducing the subsequent round trips to the database and provides the data from the stored cache. The data can be directly retrieved for all the users from the cache instead of calling the results from database. Entity Framework helps to provide the mechanism of keeping the results into a cache with the help of Redis and NCache as a second level support of distributed caching services. A distributed cache synchronizes all the instances that are generated by the multiple applications in .NET. It either works in two different modes depending upon the choice of the developer, by analyzing the frequency of the queries requested by the users or store the results at the time of fetching records from the database. It is a tradeoff between the performance and storage of an application, since the caching requires more space to store the results.

Facebook
Twitter
LinkedIn

Our website uses cookies that help it to function, allow us to analyze how you interact with it, and help us to improve its performance. By using our website you agree by our Terms and Conditions and Privacy Policy.