Phi*_*umi 8 c# sql sql-server instrumentation entity-framework
我们在我们的商店中使用Dapper和EF,并且当出现问题时,Dapper证明在SQL服务器中调试查询非常有帮助.我们创建了一个瘦装饰器,而不仅仅是提交原始SQL,它还添加了一些上下文信息(原点)作为SQL注释,类似于
/* Foo.Bar.GetOrders() */ SELECT * FROM Order WHERE orderId > 123
Run Code Online (Sandbox Code Playgroud)
这使我们的DBA和开发人员能够非常快速地进行反应并找到问题的根源,如果我们有错误的数据库调用,或者引入性能命中(我们每天有数十万个数据库调用,所以一个错误的查询会导致很多损伤).
我们也想用EF做这件事.它不一定是SQL注释,而是某种钩子,以便提供随调用一起提交的元信息.不知道这是否可行?
谢谢你的建议
菲利普
事实证明,使用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)
{
}
}
Run Code Online (Sandbox Code Playgroud)
为了使上述拦截器能够正常运行,我仅向静态DbInterception类注册了它:
DbInterception.Add(new DebugCommentInterceptor());
Run Code Online (Sandbox Code Playgroud)