Welcome

首页 / 软件开发 / .NET编程技术 / 如何使用EntityFramework 6.1的DbCommandInterceptor拦截生成的SQL语句

如何使用EntityFramework 6.1的DbCommandInterceptor拦截生成的SQL语句2015-12-29 cnblogs Ax0ne开始

EF6.1也出来不少日子了,6.1相比6.0有个很大的特点就是新增了System.Data.Entity.Infrastructure.Interception 命名空间,此命名空间下的对象可以允许我们更加方便的了解到EF运行时的一些信息,当然我们最想看的还是EF生成的Sql语句,话不多讲,开始干吧;

class EFIntercepterLogging : DbCommandInterceptor
{
private readonly Stopwatch _stopwatch = new Stopwatch();
public override void ScalarExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
base.ScalarExecuting(command, interceptionContext);
_stopwatch.Restart();
}
public override void ScalarExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
_stopwatch.Stop();
if (interceptionContext.Exception != null)
{
Trace.TraceError("Exception:{1} --> Error executing command: {0}", command.CommandText, interceptionContext.Exception.ToString());
}
else
{
Trace.TraceInformation(" 执行时间:{0} 毫秒 -->ScalarExecuted.Command:{1} ", _stopwatch.ElapsedMilliseconds, command.CommandText);
}
base.ScalarExecuted(command, interceptionContext);
}
public override void NonQueryExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
base.NonQueryExecuting(command, interceptionContext);
_stopwatch.Restart();
}
public override void NonQueryExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
_stopwatch.Stop();
if (interceptionContext.Exception != null)
{
Trace.TraceError("Exception:{1} --> Error executing command: {0}", command.CommandText, interceptionContext.Exception.ToString());
}
else
{
Trace.TraceInformation(" 执行时间:{0} 毫秒 -->NonQueryExecuted.Command: {1}", _stopwatch.ElapsedMilliseconds, command.CommandText);
}
base.NonQueryExecuted(command, interceptionContext);
}
public override void ReaderExecuting(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
{
base.ReaderExecuting(command, interceptionContext);
_stopwatch.Restart();
}
public override void ReaderExecuted(System.Data.Common.DbCommand command, DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext)
{
_stopwatch.Stop();
if (interceptionContext.Exception != null)
{
Trace.TraceError("Exception:{1} --> Error executing command: {0}", command.CommandText, interceptionContext.Exception.ToString());
}
else
{
Trace.TraceInformation(" 执行时间:{0} 毫秒 -->ReaderExecuted.Command: {1}", _stopwatch.ElapsedMilliseconds, command.CommandText);
}
base.ReaderExecuted(command, interceptionContext);
}
}
上面这段代码需要命名空间:

using System.Data.Entity.Infrastructure.Interception;
using System.Diagnostics;