Entity-framework-command-interception

提供:Dev Guides
移動先:案内検索

Entity Framework-コマンド代行受信

Entity Framework 6.0には、 Interceptor またはInterceptionと呼ばれる別の新機能があります。 インターセプトコードは、*インターセプションインターフェイス*の概念に基づいて構築されています。 たとえば、IDbCommandInterceptorインターフェイスは、EFがExecuteNonQuery、ExecuteScalar、ExecuteReader、および関連するメソッドを呼び出す前に呼び出されるメソッドを定義します。

  • Entity Frameworkはインターセプトを使用することで真に輝きます。 このアプローチを使用すると、コードを乱雑にすることなく、より多くの情報を一時的にキャプチャできます。
  • これを実装するには、独自のカスタムインターセプターを作成し、それに応じて登録する必要があります。
  • IDbCommandInterceptorインターフェイスを実装するクラスが作成されると、DbInterceptionクラスを使用してEntity Frameworkに登録できます。
  • IDbCommandInterceptorインターフェイスには6つのメソッドがあり、これらすべてのメソッドを実装する必要があります。 これらのメソッドの基本的な実装は次のとおりです。

IDbCommandInterceptorインターフェースが実装されている次のコードを見てみましょう。

public class MyCommandInterceptor : IDbCommandInterceptor {

   public static void Log(string comm, string message) {
      Console.WriteLine("Intercepted: {0}, Command Text: {1} ", comm, message);
   }

   public void NonQueryExecuted(DbCommand command,
      DbCommandInterceptionContext<int> interceptionContext) {
         Log("NonQueryExecuted: ", command.CommandText);
   }

   public void NonQueryExecuting(DbCommand command,
      DbCommandInterceptionContext<int> interceptionContext) {
         Log("NonQueryExecuting: ", command.CommandText);
   }

   public void ReaderExecuted(DbCommand command,
      DbCommandInterceptionContext<DbDataReader> interceptionContext) {
         Log("ReaderExecuted: ", command.CommandText);
   }

   public void ReaderExecuting(DbCommand command,
      DbCommandInterceptionContext<DbDataReader> interceptionContext) {
         Log("ReaderExecuting: ", command.CommandText);
   }

   public void ScalarExecuted(DbCommand command,
      DbCommandInterceptionContext<object> interceptionContext) {
         Log("ScalarExecuted: ", command.CommandText);
   }

   public void ScalarExecuting(DbCommand command,
      DbCommandInterceptionContext<object> interceptionContext) {
         Log("ScalarExecuting: ", command.CommandText);
   }

}

インターセプターの登録

1つ以上のインターセプションインターフェイスを実装するクラスが作成されると、次のコードに示すように、DbInterceptionクラスを使用してEFに登録できます。

DbInterception.Add(new MyCommandInterceptor());

インターセプターは、次のコードに示すように、DbConfigurationコードベースの構成を使用してアプリドメインレベルで登録することもできます。

public class MyDBConfiguration : DbConfiguration {

   public MyDBConfiguration() {
      DbInterception.Add(new MyCommandInterceptor());
   }
}

また、コードを使用してインターセプター構成ファイルを構成することができます-

<entityFramework>
   <interceptors>
      <interceptor type = "EFInterceptDemo.MyCommandInterceptor, EFInterceptDemo"/>
   </interceptors>
</entityFramework>