实体框架 – 命令拦截
实体框架 – 命令拦截
在 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>