[英]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
,但為了問題,我希望保持簡單)以便我可以將它傳遞給Log
的Message
屬性。
此代碼略有調整,取自這個博客。
你可以把它變成一個列表......
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.