2016-11-02 33 views

回答

3

我實現了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

好,但如果你繼承'DbCommandInterceptor'類,所以你不必會更容易覆蓋不需要的方法。 –

+0

伊萬,謝謝!使用您的建議更改了答案。 –