實體框架 - 命令攔截



在 Entity Framework 6.0 中,有一個新的功能稱為攔截器或攔截。攔截程式碼圍繞攔截介面的概念構建。例如,IDbCommandInterceptor 介面定義了在 EF 呼叫 ExecuteNonQuery、ExecuteScalar、ExecuteReader 和相關方法之前呼叫的方法。

  • 透過使用攔截,實體框架可以真正發揮其優勢。使用這種方法,您可以捕獲更多瞬態資訊,而無需弄亂您的程式碼。

  • 要實現此功能,您需要建立自己的自定義攔截器並相應地註冊它。

  • 一旦建立了實現 IDbCommandInterceptor 介面的類,就可以使用 DbInterception 類將其註冊到實體框架中。

  • 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 基於程式碼的配置在應用程式域級別註冊攔截器,如下面的程式碼所示。

public class MyDBConfiguration : DbConfiguration {

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

您還可以使用以下程式碼配置攔截器配置檔案 -

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

© . All rights reserved.