如何读取Dapper生成的SQL查询? [英] How to read an SQL query generated by Dapper?
问题描述
我有一个标准代码:
public IEnumerable ExperimentSelect(object parameters)
{
using (var connection = new SqlConnection(ConnectionString))
{
connection.Open();
var dynamicparam = new DynamicParameters(parameters);
var rows = connection.Query("[dbo].[ptbSapOrderSelect]", dynamicparam,
commandType: CommandType.StoredProcedure);
if (rows.Any())
TotalRows = ((long)rows.ToList()[0].TotalRows);
return rows;
}
}
如何使用NLog将由Dapper生成的查询自动保存到文件中?我正在考虑获取SQL Server Profiler中显示的SQL查询源.
How to automate saving queries generated by Dapper to the file using eg NLog? I am thinking of getting source of SQL query as shown in the SQL Server Profiler.
推荐答案
我设法使用 MiniProfiler.
首先,根据文档配置MiniProfiler.确保将SqlConnection包装在ProfiledDbConnection中.
First, configure MiniProfiler as per the docs. Make sure that you are wrapping your SqlConnection inside a ProfiledDbConnection.
请注意,您无需启用可视窗口小部件即可正常工作,只需确保在每个请求之前启动配置文件,然后在每个请求之后终止配置文件.
Note that you don't need to enable the visual widget for this to work, just ensure that a profile is started before, and ended after, each request.
接下来,在该请求的配置文件停止的global.asax.cs中,对其进行如下修改:
Next, in global.asax.cs where the profile for that request is stopped, amend it as follows:
protected void Application_EndRequest()
{
// not production code!
MiniProfiler.Stop();
var logger = NLog.LogManager.GetCurrentClassLogger();
var instance = MiniProfiler.Current;
if (instance == null) return;
var t = instance.GetSqlTimings();
foreach (var sqlTiming in t)
{
logger.Debug(sqlTiming.CommandString);
}
}
这实际上是转储执行的SQL命令,但是如果您想报告更多高级信息,则模型中包含很多信息.
This literally dumps the SQL command executed, but there is a lot more information included in the model if you want to report more advanced information.
这篇关于如何读取Dapper生成的SQL查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!