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 interceptionContext)
{
base.NonQueryExecuted(command, interceptionContext);
Console.WriteLine(command.CommandText);
}

public override void ReaderExecuted(DbCommand command, DbCommandInterceptionContext interceptionContext)
{
base.ReaderExecuted(command, interceptionContext);
Console.WriteLine(command.CommandText);
}

public override void ScalarExecuted(DbCommand command, DbCommandInterceptionContext 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 Users { get; set; }
}

It's all.

posted @ 2017-05-01 22:33  会长  阅读(221)  评论(0)    收藏  举报