C# 遍历DbCommand中的参数
我试图截取所有C# 遍历DbCommand中的参数,c#,entity-framework,logging,interceptor,sqlcommand,C#,Entity Framework,Logging,Interceptor,Sqlcommand,我试图截取所有SQL命令并将其记录到数据库中。我还需要参数和它们的值。但是command.Parameters没有IEnumerable。我可以为声明写一篇,,但感觉有点倒退 public override void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext) { _stopwatch.Stop(); if (intercepti
SQL
命令并将其记录到数据库中。我还需要参数和它们的值。但是command.Parameters
没有IEnumerable
。我可以为声明写一篇,
,但感觉有点倒退
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);
}
public override void scalarecuted(DbCommand命令,DbCommandInterceptionContext interceptionContext)
{
_秒表;
if(interceptOnContext.Exception!=null)
{
_Error(interceptionContext.Exception,“执行命令时出错:{0}”,command.CommandText);
string param=string.Empty;
如果(command.Parameters.Count>0)
{
foreach(command.Parameters中的var t)
{
参数+=t。。。。
}
}
日志=新日志()
{
日期=DateTime.UtcNow,
LogLevel=LogLevel.Error,
Message=command.CommandText+“\r\n”+参数。
};
}
其他的
_logger.TraceApi(“SQL数据库”,“CommandInterceptor.ScalarExecuted”,“stopwatch.appeased”,“Command:{0}:”,Command.CommandText);
ScalarExecuted(命令,拦截上下文);
}
我需要构建一个字符串
(我知道我应该为参数
使用StringBuilder
,而不是string
,但是为了这个问题,我想保持它的简单性),这样我就可以将它传递给日志
的消息
属性
这段代码稍作调整,取自博客。您可以将其列为一个列表
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());
StringBuilder sb=新建StringBuilder();
command.Parameters.Cast()
托利斯先生()
.ForEach(p=>sb.Append(
string.Format(“{0}={1}{2}”,
p、 参数名,
p、 价值观,
环境(新线),;
Console.WriteLine(sb.ToString());
为什么不使用EF 6的内置日志功能?它将传递所有SQL语句及其参数名/值。兰德,这正是我正在使用的,但是你粘贴的链接是用NLog第三方库实现的。我粘贴的链接没有使用第三方库。这两个博客都是关于拦截sql
命令的。谢谢,非常整洁。完全忽略了Cast()
。