如何将OPTION RECOMPILE添加到Entity Framework中

时间:2016-11-02 18:17:22

标签: entity-framework

我有时会遇到parameter sniffing问题。 所以我想在查询结束时添加OPTION(RECOMPILE)来修复它。 我怎么能在EF 6中做到这一点?

2 个答案:

答案 0 :(得分:10)

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

新拦截器的使用:

  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);
  }
}

答案 1 :(得分:0)

如果您在这里并且正在使用 EF Core,则可以添加拦截器并在查询中标记它们。超级简单,但有时很难找到参考资料。

https://docs.microsoft.com/en-us/ef/core/logging-events-diagnostics/interceptors