Entity Framework - 命令拦截

在Entity Framework 6.0中,还有另一个新功能,即拦截器或拦截.拦截代码围绕拦截接口的概念构建.例如,IDbCommandInterceptor接口定义在EF调用ExecuteNonQuery,ExecuteScalar,ExecuteReader和相关方法之前调用的方法.

  • 实体框架可以通过拦截真正发挥作用.使用这种方法,您可以瞬间捕获更多信息,而无需排除代码.

  • 要实现这一点,您需要创建自己的自定义拦截器并注册相应地.

  • 一旦创建了实现IDbCommandInterceptor接口的类,就可以使用DbInterception类向Entity Framework注册.

  • IDbCommandInterceptor接口有六种方法,您需要实现所有这些方法.以下是这些方法的基本实现.

让我们看看下面的代码,其中实现了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);
   }

}

注册拦截器

一旦实现了一个类已创建一个或多个拦截接口,可以使用DbInterception类向EF注册,如下面的代码所示.

DbInterception.Add(new MyCommandInterceptor());

也可以使用DbConfiguration基于代码的配置在app-domain级别注册拦截器,如下面的代码所示.

public class MyDBConfiguration : DbConfiguration {

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

您还可以使用代码配置拦截器配置文件 :

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