C# 拦截器 分享一个 .NET 通过监听器拦截 EF 消息写日志的详细例子 - 程序员的才智是无限的,虽然 EF 有这个那个的问题,但程序员却总比这些问题多一个办法
前言
EF 开发效率确实很高也很便捷,但当它发生错误时,也挺让人头疼的,为什么?因为 EF 就像是一个黑盒子,一切全被封装起来,出错的时候很难定位原因,如果能够知道并打印 EF 生成的 SQL 语句,对于定位 EF 错误,就很有帮助。
程序员的才智是无限的,虽然 EF 有这个那个的问题,但程序员却总比这些问题多一个办法。
下面分享一个 .NET 通过监听器拦截 EF 消息写日志的详细例子。
Step By Step 步骤
创建自定义监听器类,拦截 EF 的命令执行事件(留意注释) ///
/// 监听并写 EF 生成的 SQL 到日志
///
public class EFIntercepterLogging : IDbCommandInterceptor
{
///
/// 实现接口的 NonQueryExecuting 方法
///
///
///
public void NonQueryExecuting(
DbCommand command,
DbCommandInterceptionContextinterceptionContext)
{
LogWhenExecuting(command, interceptionContext);
}
///
/// 实现接口的 NonQueryExecuted 方法
///
///
///
public void NonQueryExecuted(
DbCommand command, 拼多多帮助力入口
DbCommandInterceptionContextinterceptionContext)
{
LogIfError(command, interceptionContext);
}
///
/// 实现接口的 ReaderExecuting 方法
///
///
///
public void ReaderExecuting(
DbCommand command,
DbCommandInterceptionContextinterceptionContext)
{
LogWhenExecuting(command, interceptionContext);
}
///
/// 实现接口的 ReaderExecuted 方法
///
///
///
public void ReaderExecuted(
DbCommand command,
DbCommandInterceptionContextinterceptionContext)
{
LogIfError(command, interceptionContext);
}
///
/// 实现接口的 ScalarExecuting 方法
///
///
///
public void ScalarExecuting(
DbCommand command,
DbCommandInterceptionContext