如何配置实体框架缓存?

使用实体框架进行缓存

实体框架是 ADO.NET 中支持开发面向数据的软件应用程序的一组技术。 使用实体框架,开发人员在处理数据时可以在更高的抽象级别上工作,并且可以使用比传统应用程序更少的代码来创建和维护面向数据的应用程序。

NCache 介绍了在实体框架和数据源之间起作用的缓存提供程序。 背后的主要原因 EF 缓存提供程序 是减少数据库访问(这会降低应用程序性能)并从缓存中提供查询结果。 提供程序在 ADO.NET 实体框架和原始数据源之间起作用。 因此,可以在不更改/编译当前代码的情况下插入缓存提供程序。

集成模式

NCache 实体框架缓存提供程序在两种模式下工作。 它可以在“高速缓存“或在”分析" 模式。在缓存模式下,您可以缓存所选查询的结果集。分析模式在传递模式下工作,并通过生成显示哪些查询以何种频率被调用的报告来帮助您找到应该缓存的查询。 有关集成模式的更多帮助

数据库同步

NCache 实体框架提供程序还确保缓存中的数据始终与数据库同步。 所以 NCache 使用 .NET SqlCache依赖 它向 SQL Server 注册 SQL 查询,因此如果数据库中由该查询表示的数据集中的任何行发生更改,SQL Server 会向 NCache. NCache 然后从缓存中删除相应的结果集。

如何整合 NCache 与实体框架?

前提课程:

1. 你应该有一个实体框架应用程序。 (您也可以使用示例应用程序进行 EFCaching 从 NCache 来自以下路径的示例应用程序:
“安装目录:/ProgramFiles/NCache/samples/clr20/EntityDataModelIntegrationDemo"

在每个实体框架应用程序中,已经添加了 ADO.NET 实体数据模型,它会自动生成两个文件:

  • 固态硬盘
  • 应用程序(或 Web)配置文件

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

3. 数据库工具(如MS SQL SERVER 2008、ORACLE)

启用步骤 NCache 高速缓存

第 1 步:添加参考

地址 Alachisoft.Integrations.EntityFramework.CachingProvider 引用您的实体框架应用程序。 此 .dll 文件位于以下路径:
"安装目录:/ProgramFiles/NCache/集成/MSEntityFramework"
添加引用后,需要在 3 个不同的文件中进行更改:

第 2 步:SSDL 配置(适用于 Entity Framework 3.5 和 4.0)

在实体框架应用程序中添加 ADO.NET 实体数据模型时生成的 SSDL 文件中,需要进行以下更改:

以下是 SQL 2008 数据库的示例更改;

在 SSDL 中,提供者名称在元素如下图:

[现有代码]

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

为了注入我们的 NCache 实体框架提供者,我们需要覆盖上面突出显示的属性来插入我们的提供者。 在 SSDL 中,我们将新提供者的名称放在 Provider 属性中,并将之前的提供者与我们的提供者清单令牌连接到 提供者清单令牌 字段,如下图:

[更改代码]

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

第 3 步:应用程序(或 Web)配置

在实体框架应用程序中添加 ADO.NET 实体数据模型时生成的应用程序(或 Web)配置文件需要进行以下更改:

实体框架 3.5 和 4.0

  • 在应用程序或 Web 配置文件的连接字符串中指定提供程序不变名称:

    <connectionStrings>
        <add name="NorthwindEntities" 
        connectionString="metadata=res://*/NorthwindCustomerModel.csdl
        |res://*/NorthwindCustomerModel.ssdl
        |res://*/NorthwindCustomerModel.msl;
        provider=System.Data.EntityClient;
        provider connection string="
        Data Source=localhost;Initial Catalog=Northwind;user id= userid;
        password=password;MultipleActiveResultSets=True"" 
        providerName="System.Data.EntityClient"/>
    </connectionStrings>
  • 将提供者名称更改为 NCache Entity Framework Provider 并在连接字符串中添加提供者包装信息,如下所示:

    <connectionStrings>
        <add name="NorthwindEntities" 
        connectionString="metadata=res://*/NorthwindCustomerModel.csdl
        |res://*/NorthwindCustomerModel.ssdl
        |res://*/NorthwindCustomerModel.msl;
        provider=Alachisoft.Integrations.EntityFramework.CachingProvider;
        provider connection string="
        wrappedProvider=System.Data.SqlClient;        
        Data Source=localhost;Initial Catalog=Northwind;user id= userid;
        password=password;MultipleActiveResultSets=True"" 
        providerName="System.Data.EntityClient"/>
    </connectionStrings>
    
  • 还添加提供程序工厂以初始化 NCache 实体框架提供者。 不变属性应与连接字符串中的提供者名称相同。

  • <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>
    

实体框架6.0

  • 提供程序不变名称也在应用程序(或 Web)配置文件中指定:

    <entityFramework>
        <providers>
    		<provider invariantName="System.Data.SqlClient"
          type="System.Data.Entity.SqlServer.SqlProviderServices,
           EntityFramework.SqlServer" />
        </providers>
    </entityFramework>
  • 将不变名称更改为 EFCachingProviderServices 并输入 Alachisoft.NCache.Integrations.EntityFramework.EFCachingProviderServices, Alachisoft.Integrations.EntityFramework.CachingProvider 如下图所示:

  • <entityFramework>
        <providers>
            <provider invariantName="EFCachingProviderServices" 
            type="Alachisoft.NCache.Integrations.EntityFramework.EFCachingProviderServices,
             Alachisoft.Integrations.EntityFramework.CachingProvider" />
        </providers>
    </entityFramework>

    实体框架6.1

  • 在应用程序(或 Web)配置文件的提供程序部分添加拦截器:

    <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>
    
  • 应在 appSettings 的 appSettings 中添加以下信息 app.config/web.config:

    <appSettings> <add key = "app-id" value = "PersonNameApp2"/> <add key = "logging-level" value = "Debug"/> </appSettings>
    
    1. 应用程式编号 :这将是当前应用程序的标识符。 此 ID 将用于从 efcaching.ncconf 读取配置
    2. 日志级别 :确定应用程序的日志记录级别。 仅当级别设置为时,我们的提供程序才会记录异常和错误 误差. 当级别设置为调试时,将记录异常/错误和其他详细信息。 如果级别设置为,则不会记录任何内容 关闭 (默认)。 生成日志文件的路径:默认 = /日志文件/efcaching日志/
    3. 为了应用上述更改,应在进行这些更改后重新启动应用程序

注意: efcaching.ncconf 的 App-id 应与应用程序(app.config)中的相同,否则会提示错误)

替代方法

实体框架 3.5 或 4.0

除了在 app.config/web.config 中指定连接字符串外,还可以在创建时指定连接 ObjectContext or EntityConnection. 以编程方式创建连接字符串时,包装信息必须包含在连接字符串中。 以下是如何创建连接字符串和 ObjectContext or EntityConnection 可以初始化。

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
  }

实体框架6.0

除了在 app.config/web.config 中指定提供者不变量外,还可以在初始化配置时指定提供者不变量(类继承 DbConfiguration)。 以下是如何指定提供者不变量:

try
{
    this.SetProviderServices("EFCachingProviderServices", EFCachingProviderServices.Instance);
}
catch (Exception ex)
{ 
    // handle exception
}

实体框架 6.1

除了在 app.config/web.config 中指定数据库拦截器外,还可以在初始化配置时指定数据库拦截器(类继承 DbConfiguration)。 以下是如何指定拦截器:

try
{
    this.AddInterceptor(new EFCommandInterceptor());
}
catch (Exception ex)
{ 
    // handle exception
}

通过 API(6.0 和 6.1)

用户现在还可以使用为提供的扩展名缓存结果 IQueryable.

  • 指定命名空间

    using Alachisoft.NCache.Integrations.EntityFramework.Caching;
  • 现在从调用缓存方法重载 IQueryable

    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
    	}

第 4 步:efcaching.ncconf 配置:

“efcaching.ncconf”中所需的更改。

  1. Efcaching.ncconf 放在以下路径:“Installeddirectory:/Program Files/NCache/配置”。
  2. Provider Configuration 包含缓存和缓存策略相关信息。 以下是 efcaching.ncconf 中所需的更改。

    <configuration>
          <app-config app-id = "PersonNameApp" mode = "analysis|caching">
  3. “分析”模式用于监控每个查询执行的次数,然后生成报告。 报告包含查询文本和每个查询的调用计数。 此报告可用于自定义策略。 在此模式下不进行缓存。

    <analysis-policy log-path = "" analysis-time = "1min" cache-enable-threshold = "1" default-expiration-type = "Sliding" default-expiration-time = "180sec" dbsyncdependency= "false"/>
  4. Log-path:生成分析日志文件的路径。
    默认 = < 安装目录 > /日志文件/efcaching分析日志/

  5. 对于“缓存”模式,包装提供程序将缓存所有指定查询的结果。 两种策略都有自己的规范。 每当在相应的数据库中检测到更新(UPDATE、INSERT 或 DELETE)时,提供程序通过逐出依赖于任何更新表的所有缓存查询来使受影响的缓存条目无效。

    <cache-policy-configuration database = "none|sqlserver|oracle" cache-id = "mycache">  
  6. 对于自定义策略,它包括用户可配置的查询列表,这些查询应该与其结果一起缓存。 只有那些启用了缓存的查询结果才会被缓存。 您可以为所有查询指定自定义缓存策略。

    <!--sql-query = "SELECT [Extent1].[CustomerID] AS [CustomerID],= @param_0"-->
    	<query>
            <cache-query query text="SELECT [Extent1].[OrderID] AS [OrderID], < @param_0"/>
                <cache-policy vary-by-cache-param="param_0" expiration-type="Sliding"
                 enabled="True" expiration-time="180sec" dbsyncdependency="False"/>
    	</query>
  7. 对于存储过程,查询文本将是存储过程的名称,并且没有默认策略或数据库同步依赖性。 用户可以只缓存过期的存储过程结果,这里不需要数据库依赖。

  8. 对于 API 级别缓存(在 Entity Framework 6.0 和 6.1 中支持),您可以使用命名空间中提供的扩展方法缓存查询
    using Alachisoft.NCache.Integrations.EntityFramework.Caching;
    并且您可以在以下标记中的配置文件中提供 API 级别缓存的缓存策略:

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

联系我们

联系电话
©版权所有 Alachisoft 2002 - 版权所有。 NCache 是 Diyatech Corp. 的注册商标。