IDbCommandInterceptor的实现似乎在生产服务器上造成了令人难以置信的高工作负载(从+ -20%到+80%)。
有趣的是,拦截过程中什么也没做。第一个想法是将跟踪添加到Entity Framework生成的SQL中,以便我们可以轻松地跟踪监视操作(该操作创建了SQL)。这是通过将部分调用堆栈作为注释添加到SQL来完成的,但这似乎在服务器上造成了极大的工作量,因此将代码放入注释中,从而留下一个空类,如下所示。
我没有从上下文中删除拦截器,因为我认为它不会有任何影响,但显然有影响。有谁知道为什么会有如此巨大的影响?
public class EntitiesDbInterceptor: IDbCommandInterceptor
{
public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
}
public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
AddSourceTracingToSqlQuery(command);
}
public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
}
public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
AddSourceTracingToSqlQuery(command);
}
public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
}
public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
AddSourceTracingToSqlQuery(command);
}
private void AddSourceTracingToSqlQuery(DbCommand dbCommand)
{
//try
//{
// var builder = new StringBuilder();
// var stack = new StackTrace(true);
// builder.Append("\r\n\r\n/********************* \r\n\r\n Entity Framework source trace: \r\n\r\n * ");
// var formattedStackTrace = string.Join("\r\n * ",
// from f in stack.GetFrames().Skip(2)
// let m = f?.GetMethod()
// where f?.GetFileLineNumber() != 0
// select m?.DeclaringType?.Name + "." + m?.Name + ":" + f?.GetFileLineNumber()
// );
// builder.Append(formattedStackTrace);
// builder.Append("\r\n*********************/\r\n\r\n");
// dbCommand.CommandText = builder.ToString() + dbCommand.CommandText;
//}
//catch (Exception)
//{
// throw;
//}
}
}