- 實體框架教程
- 實體框架 - 首頁
- 實體框架 - 概述
- 實體框架 - 架構
- 實體框架 - 環境設定
- 實體框架 - 資料庫設定
- 實體框架 - 資料模型
- 實體框架 - DbContext
- 實體框架 - 型別
- 實體框架 - 關係
- 實體框架 - 生命週期
- 實體框架 - 程式碼優先方法
- 實體框架 - 模型優先方法
- 實體框架 - 資料庫優先方法
- 實體框架 - 開發方法
- 實體框架 - 資料庫操作
- 實體框架 - 併發
- 實體框架 - 事務
- 實體框架 - 檢視
- 實體框架 - 索引
- 實體框架 - 儲存過程
- 實體框架 - 斷開連線的實體
- 實體框架 - 表值函式
- 實體框架 - 原生 SQL
- 實體框架 - 列舉支援
- 實體框架 - 非同步查詢
- 實體框架 - 持久化
- 實體框架 - 投影查詢
- 實體框架 - 命令日誌記錄
- 實體框架 - 命令攔截
- 實體框架 - 空間資料型別
- 實體框架 - 繼承
- 實體框架 - 遷移
- 實體框架 - 渴望載入
- 實體框架 - 延遲載入
- 實體框架 - 顯式載入
- 實體框架 - 驗證
- 實體框架 - 跟蹤更改
- 實體框架 - 彩色實體
- 實體框架 - 程式碼優先方法
- 實體框架 - 第一個示例
- 實體框架 - 資料註解
- 實體框架 - Fluent API
- 實體框架 - 種子資料庫
- 實體框架 - 程式碼優先遷移
- 實體框架 - 多個 DbContext
- 實體框架 - 巢狀實體型別
- 實體框架資源
- 實體框架 - 快速指南
- 實體框架 - 有用資源
- 實體框架 - 討論
實體框架 - 命令攔截
在 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>
廣告