从 Entity Framework 6 中查看查询参数

Viewing Query Parameters from Entity Framework 6 Logging

我已将我的 Database First EF6 DbContext 配置为记录它生成的查询,但我注意到它提供的查询已参数化。出于调试目的,我想输出每个参数的值。我写了一个拦截器 class 并将其配置为像下面的代码片段一样输出参数,但它仍然不输出参数值。我究竟做错了什么?为 Entity Framework 生成的查询输出参数值的正确方法是什么。我知道在 EF Core 中 OptionsBuilder 上有一个设置可以启用敏感数据的日志记录,但我在 EF6 中找不到任何类似的设置。

public class LoggingInterceptor : DatabaseLogFormatter {
        public LoggingInterceptor(DbContext context, Action<string> writeAction) : base(context,writeAction) {

        }

        public override void LogCommand<TResult>(DbCommand command, DbCommandInterceptionContext<TResult> interceptionContext)
        {
            var sql = new StringBuilder();
            sql.Append(command.CommandText);
            sql.Append("\n");
            foreach (var param in command.Parameters) {
                sql.Append(param.ToString());
                sql.Append("\n");
            }
            Write($"Entity Framework SQL : {sql}");
        }

    public override void LogResult<TResult>(DbCommand command, DbCommandInterceptionContext<TResult> interceptionContext){}
}

你不需要做任何特殊的事情(比如你的 inerceptor),如果你在查询到数据库之前添加这段代码,你将在 [=] 的输出 window 上得到查询和参数13=]:

context.Database.Log = x => System.Diagnostics.Debug.WriteLine(x);