entity-framework - 如何将 OPTION RECOMPILE 添加到 Entity Framework 中

标签 entity-framework

我正在经历parameter sniffing有时会出现问题。 所以我想在查询末尾添加选项(重新编译)来修复它。 我怎样才能在 EF 6 中做到这一点?

最佳答案

我实现了IDbCommandInterceptor接口(interface)来修复参数嗅探错误。

新拦截器的用法:

  using (var dataContext = new AdventureWorks2012Entities())
  {
    var optionRecompileInterceptor = new OptionRecompileInterceptor();
    DbInterception.Add(optionRecompileInterceptor);

    string city = "Seattle";
    var seattle = (
      from a in dataContext.Addresses
      where a.City == city
      select a).ToList();

    DbInterception.Remove(optionRecompileInterceptor); //Remove interceptor to not affect other queries
  }

拦截器的实现:

public class OptionRecompileInterceptor : DbCommandInterceptor
{
  static void AddOptionToCommand(DbCommand command)
  {
    string optionRecompileString = "\r\nOPTION (RECOMPILE)";
    if (!command.CommandText.Contains(optionRecompileString)) //Check the option is not added already
    {
      command.CommandText += optionRecompileString;
    }
  }


  public override void NonQueryExecuting(
    DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
  {
    AddOptionToCommand(command);
  }

  public override void ReaderExecuting(
    DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
  {
    AddOptionToCommand(command);
  }

  public override void ScalarExecuting(
    DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
  {
    AddOptionToCommand(command);
  }
}

关于entity-framework - 如何将 OPTION RECOMPILE 添加到 Entity Framework 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40387037/

相关文章:

c# - EntityFramework.Extend 与 LinqPad 一起使用吗?

oracle - EF + ODP.NET : The specified value is not an instance of type 'Edm.Decimal'

c# - 如何使用 EF 在我的 asp.net core 3.1 MVC 应用程序中正确使用我的 SQLite db?

entity-framework - 在 Entity Framework 代码中,有没有办法向导航集合添加分页?

c# - 在配置中找不到提供程序或无效错误

entity-framework - 使用 moq 单元测试 Entity Framework

c# - 如何更改View中的显示文本?

c# - 错误消息将使用枚举与 EF 和 Web API

visual-studio - 如何为 Visual Studio 2017 安装 Entity Framework Power Tools?

c# - 基于泛型参数实例化具体类c#