Lerning Entity Framework 6 ------ Using a commandInterceptor
Sometimes, We want to check the original sql statements. creating a commandInterceptor is a good way to do this.
Add a class named MyCommandInterceptor
class MyCommandInterceptor: DbCommandInterceptor
{
public override void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
base.NonQueryExecuted(command, interceptionContext);
Console.WriteLine(command.CommandText);
}
public override void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
base.ReaderExecuted(command, interceptionContext);
Console.WriteLine(command.CommandText);
}
public override void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
base.ScalarExecuted(command, interceptionContext);
Console.WriteLine(command.CommandText);
}
}
The namespace System.Data.Entity.Infrastructure.Interception is needed. Then Add DbInterception.Add(new MyCommandInterceptor());
in your constructor of DbContext class:
public class MyDb:DbContext
{
public MyDb():base("name=TestDb")
{
DbInterception.Add(new MyCommandInterceptor());
}
public IDbSet<User> Users { get; set; }
}
It's all.
欢迎转载,转载请注明出处