【发布时间】: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,但为了问题的缘故,我想保持简单)以便我可以将它传递给Log 的 Message 属性。
此代码稍作调整,取自this博客。
【问题讨论】:
-
为什么不使用 EF 6 的内置日志功能?它将提供所有 SQL 语句及其参数名称/值。 msdn.microsoft.com/en-us/library/dn469464.aspx
-
兰德,这正是我正在使用的,但您粘贴的链接使用 NLog 第三方库。而且我粘贴的链接不使用第三方库。两个博客都是关于拦截
sql命令的。
标签: c# entity-framework logging interceptor sqlcommand