Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read an SQL query generated by Dapper?

Tags:

c#

logging

dapper

I have a standard code:

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;
    }
}

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.

like image 589
Tomasito Avatar asked Jan 14 '13 12:01

Tomasito


People also ask

Does dapper generate SQL?

[1] Some extensions have been added to Dapper that provide minimal change tracking capability [2] Dapper actually does generate SQL, but in a limited fashion.

How do I display a SQL query?

The DISPLAY command must be placed immediately after the query statement on which you want it to take effect. For example: SELECT pno, pname FROM part WHERE color='BLUE'; DISPLAY; When the system encounters this DISPLAY command, it displays the Result window containing the part number and name for all blue parts.


1 Answers

I managed to make this work in an ASP.Net MVC app using MiniProfiler.

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.

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

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.

like image 72
gooid Avatar answered Sep 17 '22 15:09

gooid