4

I'm trying to intercept and log all SQL commands to the database. And I need the parameters and their values as well. But command.Parameters doesn't have an IEnumerable. I could go for a for-statement but kinda feels like a set back.

public override void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
    _stopwatch.Stop();
    if (interceptionContext.Exception != null)
    {
        _logger.Error(interceptionContext.Exception, "Error executing command: {0}", command.CommandText);

        string param = string.Empty;

        if (command.Parameters.Count > 0)
        {
            foreach (var t in command.Parameters)
            {
                param += t....
            }
        }

        Log log = new Log() 
        { 
            Date = DateTime.UtcNow, 
            LogLevel = LogLevel.Error, 
            Message = command.CommandText + "\r\n " + param. 
        };
    }
    else
        _logger.TraceApi("SQL Database", "CommandInterceptor.ScalarExecuted", _stopwatch.Elapsed, "Command: {0}: ", command.CommandText);

    base.ScalarExecuted(command, interceptionContext);
}

I need to build a string (I know I should use StringBuilder in stead of string for the param, but for the question's sake want to keep it simple) so that I can pass it to the Message property of Log.

This code is slightly adjusted and taken from this blog.

2
  • Why don't you use the in built log functionality of EF 6? It will deliver all SQL Statements and their parameter names/values. msdn.microsoft.com/en-us/library/dn469464.aspx May 3, 2014 at 0:16
  • Rand, that is exactly what I'm using, but the link you pasted does it with NLog a third party lib. And the link I pasted doesn't use a third party lib. Both blogs are about intercepting sql commands.
    – Quoter
    May 3, 2014 at 10:12

1 Answer 1

8

You can make it a List...

StringBuilder sb = new StringBuilder();

command.Parameters.Cast<DbParameter>()
                  .ToList()
                  .ForEach(p => sb.Append(
                                   string.Format("{0} = {1}{2}",
                                      p.ParameterName,
                                      p.Value,
                                      Environment.NewLine)));

Console.WriteLine(sb.ToString());
1
  • Thanks, very neat. Totally overlooked the Cast().
    – Quoter
    May 3, 2014 at 23:14

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.