Using MiniProfiler for direct ADO.net calls

2019-07-05 09:08发布

问题:

This question will be silly for those who are geeks in C# and profilers.

I am new to c# (basically a c++ developer) . I can profile the database queries if it use dbproviderfactory , but i cannot profile the ado.net calls when it is used directly(raw SqlConnection & SqlCommand). I came across the Miniprofiler code where they also profile direct ADO.net calls. I just dont know how to use it ( integrate it in my profiler ).

My code is

        SqlConnection myConn = new SqlConnection(@"Server=192.168.23.99;Initial Catalog=cat1;User ID=user21;Password=userpwd");
        SqlCommand myCommand = new SqlCommand("select * from table1", myConn);
        SqlDataReader dataReader;

        System.Threading.Thread.Sleep(5000);
        try
        {
            myConn.Open();
            dataReader = myCommand.ExecuteReader();

            GridView1.DataSource = dataReader;
            GridView1.DataBind();
            dataReader.Close();
            myCommand.Dispose();
            myConn.Close();
        }
        catch (System.Exception ex)
        {
            Response.Write(ex.ToString());
        }

When the above code gets executed , how will the classes in MiniProfiler will be called? How to make those classes(hope the class name is SimpleProfiledDbCommand) called when my web application calls SqlCommand(..).?

Need a better clarification on this.

回答1:

According to the documentation, you need to wrap your SqlConnection with the provided ProfiledDbConnection that is able to track your queries:

SqlConnection underlyingConn = new SqlConnection(@"Server=192.168.23.99;Initial Catalog=cat1;User ID=user21;Password=userpwd");

SqlConnection myConn = new StackExchange.Profiling.Data.ProfiledDbConnection(underlyingConn, MiniProfiler.Current);