我们在我们的商店中使用Dapper和EF,事实证明,当发生问题时,Dapper对调试SQL Server中的查询非常有帮助。我们创建了一个精简装饰器,而不是仅提交原始SQL,它还添加了一些上下文信息(源)作为SQL注释,例如
/* Foo.Bar.GetOrders() */ SELECT * FROM Order WHERE orderId > 123
如果我们有错误的数据库调用,或者引入了性能问题(这使得我们每天都有数十万个数据库调用,那么一个错误的查询会导致相当大的伤害)。
我们也想通过EF做到这一点。它不一定必须是SQL注释,而是某种挂钩可以提供随调用提交的元信息。知道这是否可能吗?
感谢您的建议
Philipp
结果证明,使用EF 6变得非常容易。所需要的只是IDbCommandInterceptor的实现,它使我能够使用自定义(SQL)注释来扩展提交的SQL。该注释将出现在数据库日志中,从而从DBA端启用调试/跟踪。
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类中注册了它:
DbInterception.Add(new DebugCommentInterceptor());
晚聚会,我不敢在上面的话题@Sixten Otto上发表评论,但您可以从this thread中找到有关如何获取呼叫者详细信息的详细信息>
如果使用EF Core,则可以使用查询标签。