将调试信息注入Entity Framework查询 [英] Inject debug information into Entity Framework queries

查看:63
本文介绍了将调试信息注入Entity Framework查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在商店中使用了Dapper和EF,事实证明,当发生问题时,Dapper对调试SQL Server中的查询非常有帮助.我们创建了一个精简的装饰器,而不是仅仅提交原始的SQL,它还添加了一些上下文信息(源)作为SQL注释,例如

We're using Dapper and EF in our shop, and Dapper proofed to be extremely helpful in debugging queries in SQL server when something went wrong. Instead of just submitting raw SQL, we created a thin decorator that also adds some context information (the origin) as an SQL comment, something like

/* Foo.Bar.GetOrders() */ SELECT * FROM Order WHERE orderId > 123

这使我们的DBA和开发人员能够迅速做出反应,并发现错误的根源(如果我们有错误的数据库调用或引入性能问题的话(每天我们有成千上万的数据库调用,因此一个错误的查询可以造成相当大的损害).

This allows our DBAs and developers to reacy very quickly and find the source of a problem if we have DB calls that are erroneous, or introduce performance hits (we have hundreds of thousands of DB calls per day, so one bad query can cause quite some damage).

我们也想通过EF做到这一点.它不必是SQL注释,而可以是某种挂钩,以提供随调用提交的元信息.知道这是否可能吗?

We would also like to do this with EF. It doesn't have to be an SQL comment, but some kind of hook in order to supply meta information that is submitted with the call. Any idea whether this is possible?

感谢您的建议

菲利普

推荐答案

事实证明,使用EF 6变得非常容易.所需要的只是 IDbCommandInterceptor 的实现,它使我能够扩大提交的内容.带自定义(SQL)注释的SQL.该注释将出现在数据库日志中,从而从DBA端启用调试/跟踪.

Turns out this becomes very easy with EF 6. All that's needed is an implementation of IDbCommandInterceptor, which allowed me to augment the submitted SQL with a custom (SQL) comment. That comment will appear in the database logs, and thus enable debugging / tracing from the DBA side.

public class DebugCommentInterceptor : IDbCommandInterceptor
{
    public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
    {
        command.CommandText = "/* TRACING INFORMATION GOES HERE */ " + command.CommandText;
    }

    public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
    {
        command.CommandText = "/* TRACING INFORMATION GOES HERE */ " + command.CommandText;
    }

    public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
    {
    }

    public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
    {
    }

    public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
    {
    }

    public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
    {
    }
}

为了使上述拦截器能够正常运行,我只是在静态 DbInterception 类中注册了它:

In order to get the above interceptor operational, I simply registered it with the static DbInterception class:

DbInterception.Add(new DebugCommentInterceptor());

这篇关于将调试信息注入Entity Framework查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆