NCache 4.4 - Online Documentation

Using NCache as Entity Framework Second Level Cache

 
Integration without any Code Change
 
NCache custom Entity Framework ADO.NET provider can be integrated in the application without any code change. Simply modify configuration files and specify NCache Entity Framework Caching Provider as second Level Cache provider.
 
Prerequisites:
 
Following are the prerequisites to enable NCache in Entity Framework application:
 
      1. The user should have an Entity Framework application. The sample application for Entity Framework Caching from NCache sample
applications can also be used from the following path
 
%InstalledDirectory%/samples/clr20/EntityDataModelIntegrationDemo
 
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, ORACLE)
 
Steps required to enable NCache as Second Level Cache Provider in Entity Framework application are follows:
 
Adding Appropriate Assemble Reference 
 
Add the following assembly
 
Alachisoft.Integrations.EntityFramework.CachingProvider
 
into Entity Framework application. This .dll file is placed on the following path:
 
%Installeddirectory%/integration/MSEntityFramework.
 
After adding the reference, the following changes are required:
 
Modifying Application or Web Configurations
 
Application or web configuration file which is generated on adding ADO.NET Entity Data Model in Entity Framework application, requires following changes:
 
Entity Framework  3.5  or 4.0
·     Provider invariant name is specified in the connection string of application or web configuration file:
                                  <connectionStrings>
                        <add name="NorthwindEntities" 
                        connectionString="metadata=res://*/NorthwindCustomerModel.csdl
                        |res://*/NorthwindCustomerModel.ssdl
                        |res://*/NorthwindCustomerModel.msl;
                        provider=System.Data.EntityClient;
                        provider connection string=&quot;
                        Data Source=localhost;Initial Catalog=Northwind;user id= userid;
                        password=password;MultipleActiveResultSets=True&quot;" 
                        providerName="System.Data.EntityClient"/>
                       </connectionStrings>
 
Change provider name to NCache Entity framework Provider and also add the provider wrapper information in    connection string as shown below:
 
<connectionStrings>
                             <add name="NorthwindEntities" 
                             connectionString="metadata=res://*/NorthwindCustomerModel.csdl
                             |res://*/NorthwindCustomerModel.ssdl
                             |res://*/NorthwindCustomerModel.msl;
                             provider=Alachisoft.Integrations.EntityFramework.CachingProvider;
                             provider connection string=&quot;
                             wrappedProvider=System.Data.SqlClient;        
                             Data Source=localhost;Initial Catalog=Northwind;user id= userid;
                             password=password;MultipleActiveResultSets=True&quot;" 
                             providerName="System.Data.EntityClient"/>
                           </connectionStrings>
 
·     Also add the provider factory for initialization of NCache Entity framework Provider. The invariant attribute should be the same as the provider name in connection string.
 
For Enterprise and Professional Editions:-
                               <DbProviderFactories>
                         <add name="EF Caching Data Provider" 
                         invariant="Alachisoft.Integrations.EntityFramework.
                         CachingProvider" 
                         description="Caching Provider Wrapper" 
                         type="Alachisoft.NCache.Integrations.
                         EntityFramework.EFCachingProviderFactory, 
                         Alachisoft.Integrations.EntityFramework.
                         CachingProvider, 
                         Version=1.0.0.0,
                         Culture=neutral,
                         PublicKeyToken=cff5926ed6a53769"/>
                    </DbProviderFactories>
 
Entity Framework 6.0
·     Provider invariant name is also specified in the application (or web) configuration file:
<entityFramework>
                            <providers>
                                  <provider invariantName="System.Data.SqlClient"
type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
                            </providers>
</entityFramework>
 
Change invariant name  to EFCachingProviderServices and  type to Alachisoft.NCache.Integrations.EntityFramework.EFCachingProviderServices,  Alachisoft.Integrations.EntityFramework.CachingProvider as shown below:
 
                      <entityFramework>
                            <providers>
                              <provider invariantName="EFCachingProviderServices"
type="Alachisoft.NCache.Integrations.EntityFramework.EFCachingProviderServices,
Alachisoft.Integrations.EntityFramework.CachingProvider" />
                            </providers>
</entityFramework>
 
 
Entity Framework 6.1
·     Add  an interceptor in provider section in the application (or web) configuration file:
<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>
 
Configuration independent of Entity Framework version   
·     The following information should be added in appSettings of app.config or web.config
 
                                  <appSettings>
                             <add key="app-id" value="EFCachingDemo"/>
                             <add key="logging-level" value="Debug"/>
                       </appSettings>
 
 
app-id: This will be the identifier for current application. This ID will be used to read configuration from efcaching.ncconf.NCache.EF Caching provider reads the required information from efcaching.ncconf on the basis of ID given in app/web .config file. 
 
logging-level: Determines the logging level for application. The provider will log exceptions and errors only when 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 is
 
%Installeddirectory%/log-files/efcaching-logs/
 
App-id of efcaching.ncconf should be the same as in application (app.config) in order to avoid an error. Application should be restarted after above changes are made.
 
Alternative method through Programming
 
      Entity Framework  3.5  or 4.0
 
Apart from specifying 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.
 
try
{
    SqlConnectionStringBuilder sqlConnBuilder =     new SqlConnectionStringBuilder();
    sqlConnBuilder.DataSource = "localhost";
    sqlConnBuilder.InitialCatalog = "EFTestDB";
    sqlConnBuilder.IntegratedSecurity = true;
    string conString = sqlConnBuilder.ToString();
    EntityConnectionStringBuilder efConnBuilder = new EntityConnectionStringBuilder();
    efConnBuilder.Provider = "EFCachingProvider";
    efConnBuilder.ProviderConnectionString = @"wrappedProvider=System.Data.SqlClient;" + conString;
    efConnBuilder.Metadata = "res:// /NorthwindCustomerModel.csdl|res:" + "// /NorthwindCustomerModel.ssdl|res:" +"// /NorthwindCustomerModel.msl;";
    EntityConnection connection = new EntityConnection(efConnBuilder.ToString());
}
catch (Exception ex)
    // handle exception
}
 
      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.
 
try
{
    this.SetProviderServices("EFCachingProviderServices", EFCachingProviderServices.Instance);
}
catch (Exception ex)
    // handle exception
}
 
      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.
 
try
{
    this.AddInterceptor(new EFCommandInterceptor());
}
catch (Exception ex)
    // handle exception
}
 
      Through API (6.0 and 6.1)
 
      User can now also cache results using extension provided for IQueryable.
 
·     Specify the namespace
 
using Alachisoft.NCache.Integrations.EntityFramework.Caching;
 
·     Call cache method overloads now from IQueryable insance
 
          var students = from s in db.Students
                          select s;
          students.Cache(); // results are not cached yet
          foreach (Student student in students) //results are cached when enumerator from query is iterated completely
          {
              //using student
          }
 
The application will need to be rebuilt the application for effectively applying the above changes.
 
Entity Framework-Caching Configuration File    
 
 
EFcaching.ncconf configuration contains cache and caching policy related information used by NCache Entity Framework caching provider. Some changes are required in "efcaching.ncconf" to run the Entity Framework Application with NCache.This config file is placed on the following path:
 
%Installeddirectory%/config
 
Below are the changes required in efcaching.ncconf.
 
<configuration>
<app-config app-id="EFCachingDemo" mode="analysis|caching">
<analysis-policy log-path="" analysis-time="1min" cache-enable-threshold="1" default-expiration-type="Sliding" default-expiration-time="180sec" dbsyncdependency="false"/>
<cache-policy-configurationdatabase="none|sqlserver|oracle" cache-id="mycache">
<api-level-caching expiration-type="sliding|absolute" enable="True|False" expiration-time="120sec" dbsyncdependency="True|False">
                   <!--sql-query = "SELECT [Extent1].[CustomerID] AS 
                [CustomerID],= @param_0"-->
<query>
                   <cache-query query text="SELECT [Extent1].
                        [OrderID] AS [OrderID], &lt; @param_0"/>
                   <cache-policy vary-by-cache-param="param_0" expiration-type="Sliding" enabled="True" 
expiration-time="180sec" dbsyncdependency="False"/>
 
                 </query>
</cache-policy-configuration>
</app-config>
</configuration>
 
       
Member
Description
 
app-id
This ID is same as defined in app/web configuration file of application.
mode
NCache Entity Framework Caching provider works under two modes. It can either be in "Caching" or in "Analysis" mode.
Analysis Mode
Analysis Mode is used for monitoring the number of times each query executes and then it generates a report. Report contains the query text and the call count for each query. No caching is done at this mode.
·     log-path: The default Path at which analysis log files will be generated is %Installeddirectory%/log-files/EFCachingAnalysisLogs/
·     analysis-time: Time for which the analysis will run. Default = 1 min
·     cache-enable-threshold: Caching will automatically be enabled for queries whose call-count exceeds this threshold. By default, its value is 1.
·     default-expiration-type: Default expiration type for analyzed queries. The default type is sliding.
·     default-expiration-time: Default expiration time for analyzed queries. Default is 180 sec (3 min)
·     dbsyncdependency: Determines whether to enable database-dependency or not. Default value is false.
 
Caching Mode
Wrapping provider will cache the results of all the specified queries. Whenever update is detected (either UPDATE, INSERT or DELETE) in a respective database, the provider invalidates the affected cache entries by evicting all cached queries which were dependent on any of the updated tables.
·     database : Database server where user’s database reside.
·     cache-id : Specified Cache Name where query results are stored for fast access.
 
query
Query attribute including user-configurable list of queries that should be cached with their results. A particular query can be configured with its cache policy defined in cache policy tag. Cache query and Cache policy are separated by dedicated tags. User can easily change policies from cache-policy tag without facing any XML parsing error.
 
cache-query
For cache query, this tag is auto generated by Entity Framework Caching Provider when the application is running  in analysis mode.  For ease of understanding, commented SQL-query tag is added so that the user can read the query.
·     cache-query-text : This is used for XML parser and the user is not allowed to make any sort of changes in it.
 
Cache-policy
When mode is selected as Caching, only those query results will be cached for which caching is enabled.  The user can also specify caching policies for all queries.
·     vary-by-cache-param: User can specify which parameter should be included as part of cache key. NCache Entity Framework Cacheing Provider will replace the actual parameter in.config file with its own names which should follow the following parameter format:
@param_[parameter-no/index]
For example,
@param_0, @param_1,@param_2;
A sample query with parameters:
"select * from dbo.customers where customer_id = @param_0 and dob > @param_1;"
·     enable : Determines whether caching is enabled for this query or not. Default value is true.
·     expiration-type: Type of expiration, it can be 'absolute' or 'sliding'. Default is sliding.
·     expiration-time: Expiration time for this query. Default is 180 sec (3 min).
·     dbsyncdependency: Determines whether to enable database-dependency for this query or not. Default is false.
 
Api-level-caching
While using the api for caching, the user can also specify caching policies for all queries he is caching using api.
·     enable : Determines whether caching is enabled for api-level-caching or not. Default value is true.
·     expiration-type: Type of expiration, it can be 'absolute' or 'sliding'. Default is sliding.
·     expiration-time: Expiration time for this query. Default is 180 sec (3 min).
·     dbsyncdependency: Determines whether to enable database-dependency for this query or not. Default is false.
 
 
 
 
SQL Dependency will be registered only for those SQL queries that satisfy all the conditions for SQL Notification Registration as described in the Microsoft provided document.
 
 
 
InProc client cache stores items in object form, therefore if object is modified by the application, it should be updated back to the cache so that other remote clustered cache and other client caches have no data integrity issue.
 
 
 
See Also