Search code examples
dapper

Is there any way to trace\log the sql using Dapper?


Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me.


Solution

  • I got the same issue and implemented some code after doing some search but having no ready-to-use stuff. There is a package on nuget MiniProfiler.Integrations I would like to share.

    Update V2: it supports to work with other database servers, for MySQL it requires to have MiniProfiler.Integrations.MySql

    Below are steps to work with SQL Server:

    1.Instantiate the connection

    var factory = new SqlServerDbConnectionFactory(_connectionString);
    using (var connection = ProfiledDbConnectionFactory.New(factory, CustomDbProfiler.Current))
    {
     // your code
    }
    

    2.After all works done, write all commands to a file if you want

    File.WriteAllText("SqlScripts.txt", CustomDbProfiler.Current.ProfilerContext.GetCommands());