簡體   English   中英

迭代DbCommand中的參數

[英]Iterate through parameters in DbCommand

我正在嘗試攔截並將所有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屬性。

此代碼略有調整,取自這個博客。

你可以把它變成一個列表......

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM