迭代DbCommand中的参数

本文关键字:参数 DbCommand 迭代 | 更新日期: 2023-09-27 18:01:30

我正试图拦截并记录所有SQL命令到数据库。我还需要参数和它们的值。但是command.Parameters没有IEnumerable。我可以选一个for-statement,但感觉有点像一个挫折。

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);
}

我需要建立一个string(我知道我应该使用StringBuilder而不是stringparam,但为了问题的缘故想保持简单),这样我就可以把它传递给LogMessage属性。

这段代码稍作调整,摘自本博客

迭代DbCommand中的参数

你可以把它做成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());