开发手册 欢迎您!
软件开发者资料库

Entity Framework - 命令拦截

Entity Framework命令拦截 - 从概述,体系结构,环境设置,数据库设置,数据模型,DbContext,类型,关系,生命周期,代码优先方法,模型优先方法,数据库优先方法,DEV方法,数据库操作,并发开始学习实体框架,事务,视图,索引,存储过程,断开连接的实体,表值函数,本机SQL,枚举支持,异步查询,持久性,投影查询,命令记录,命令拦截,空间数据类型,继承,迁移,渴望,懒惰,显式加载,验证,跟踪更改,彩色实体,第一个示例,数据注释,Fluent API,种子数据库,代码优先迁移,多个DbContext,嵌套实体类型。

在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 interceptionContext) {         Log("NonQueryExecuted: ", command.CommandText);   }   public void NonQueryExecuting(DbCommand command,       DbCommandInterceptionContext interceptionContext) {         Log("NonQueryExecuting: ", command.CommandText);   }   public void ReaderExecuted(DbCommand command,       DbCommandInterceptionContext interceptionContext) {         Log("ReaderExecuted: ", command.CommandText);   }   public void ReaderExecuting(DbCommand command,       DbCommandInterceptionContext interceptionContext) {         Log("ReaderExecuting: ", command.CommandText);   }   public void ScalarExecuted(DbCommand command,       DbCommandInterceptionContext interceptionContext) {         Log("ScalarExecuted: ", command.CommandText);   }   public void ScalarExecuting(DbCommand command,       DbCommandInterceptionContext interceptionContext) {         Log("ScalarExecuting: ", command.CommandText);   }}

注册拦截器

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

DbInterception.Add(new MyCommandInterceptor());

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

public class MyDBConfiguration : DbConfiguration {

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

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

            
2009-2025 Copyright Wonhero.Com All Rights Reserved
深圳幻海软件技术有限公司 版权所有