实体框架 - 命令拦截
在 Entity Framework 6.0 中,还有另一个新功能,称为Interceptor或 Interception。拦截代码是围绕拦截接口的概念构建的。例如,IDbCommandInterceptor 接口定义了在 EF 调用 ExecuteNonQuery、ExecuteScalar、ExecuteReader 和相关方法之前调用的方法。
Entity Framework 可以通过使用拦截真正大放异彩。使用这种方法,您可以暂时捕获更多信息,而无需弄乱代码。
要实现这一点,您需要创建自己的自定义拦截器并相应地注册它。
一旦创建了实现 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 基于代码的配置在应用程序域级别注册拦截器,如以下代码所示。
public class MyDBConfiguration : DbConfiguration {
public MyDBConfiguration() {
DbInterception.Add(new MyCommandInterceptor());
}
}
您还可以使用代码配置拦截器配置文件 −
<entityFramework>
<interceptors>
<interceptor type = "EFInterceptDemo.MyCommandInterceptor, EFInterceptDemo"/>
</interceptors>
</entityFramework>

