Search code examples
c#.netentity-framework-6

Viewing Query Parameters from Entity Framework 6 Logging


I've configured my Database First EF6 DbContext to log the queries it generates but I'm noticing that the queries it provides are parameterized. For debugging purposes I wanted to output the values of each of the parameters. I wrote an interceptor class and configured it to output the parameters like in the below code snippet, but it still doesn't output the parameter value. What am I doing wrong? What's the correct way to output the parameter values for the queries that Entity Framework generates. I know that in EF Core there's a setting on the OptionsBuilder to enable logging of sensitive data but I can't find any similar setting in 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){}
}


Solution

  • You don't need to do anything special (like your inerceptor), if you add this code before your query to the database you will get the query and the parameters on the output window of Visual studio:

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