1
我有時遇到parameter sniffing問題。 所以我想添加OPTION(RECOMPILE)到查詢的最後來修復它。 如何在EF 6中做到這一點?如何將OPTION重新添加到實體框架中
我有時遇到parameter sniffing問題。 所以我想添加OPTION(RECOMPILE)到查詢的最後來修復它。 如何在EF 6中做到這一點?如何將OPTION重新添加到實體框架中
我實現了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);
}
}
好,但如果你繼承'DbCommandInterceptor'類,所以你不必會更容易覆蓋不需要的方法。 –
伊萬,謝謝!使用您的建議更改了答案。 –