2016-11-02 9 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

イワン、ありがとう!あなたの提案を使って答えを変更しました。 –

関連する問題