Inject debug information into Entity Framework queries
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)
{
}
}
In order to get the above interceptor operational, I simply registered it with the static DbInterception class:
DbInterception.Add(new DebugCommentInterceptor());