【问题标题】:Iterate through parameters in DbCommand遍历 DbCommand 中的参数
【发布时间】:2014-06-19 17:36:51
【问题描述】:

我正在尝试拦截所有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 而不是string 作为param,但为了问题的缘故,我想保持简单)以便我可以将它传递给LogMessage 属性。

此代码稍作调整,取自this博客。

【问题讨论】:

  • 为什么不使用 EF 6 的内置日志功能?它将提供所有 SQL 语句及其参数名称/值。 msdn.microsoft.com/en-us/library/dn469464.aspx
  • 兰德,这正是我正在使用的,但您粘贴的链接使用 NLog 第三方库。而且我粘贴的链接不使用第三方库。两个博客都是关于拦截sql 命令的。

标签: c# entity-framework logging interceptor sqlcommand


【解决方案1】:

你可以把它变成一个列表...

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

【讨论】:

  • 谢谢,非常整洁。完全忽略了Cast()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-07
  • 1970-01-01
  • 1970-01-01
  • 2011-05-23
  • 1970-01-01
  • 2023-01-26
  • 2014-05-13
相关资源
最近更新 更多