Mini Profiler与SqlConnection集成

cor*_*ews 7 c# sql-server mvc-mini-profiler

我在Web表单应用程序中有一个现有的数据库连接功能,我想与迷你探查器集成.我在应用程序上安装并运行了迷你探查器,但我似乎无法正确连接数据库部分.下面是我们连接到db的代码的一部分.

public override IEnumerable<IDataRecord> Execute()
{
    using( SqlConnection conn = new SqlConnection( ConnectionString ) ) {
        using( SqlCommand command = new SqlCommand( CommandText, conn ) ) {
            command.CommandType = SQLCommandType;
            foreach( SqlParameter p in ParamsToAdd ) {
                command.Parameters.Add( p );
            }
            conn.Open();
            SqlDataReader rdr;
            try {
                rdr = command.ExecuteReader();
            } catch( Exception ex ) {
                //log error
            }
            using( rdr ) {
                while( rdr.Read() ) {
                    yield return (IDataRecord)rdr;
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以像这样轻松地绕过ExecuteReader():

using( MiniProfiler.Current.Step( command.CommandText ) ) {
    rdr = command.ExecuteReader();
}
Run Code Online (Sandbox Code Playgroud)

但这使得迷你探查器与跟踪一样有用,我想获得网站上显示的查询功能.任何帮助?

Agh*_*oub 10

您可以尝试使用此代码 - 基于ProfiledDbConnection

var connection = MiniProfiler.Data.ProfiledDbConnection.Get(new SqlConnection(str));
var cmd = connection.CreateCommand();
var param = connection.CreateParameter(); 
Run Code Online (Sandbox Code Playgroud)

链接:https://github.com/ServiceStack/ServiceStack/tree/master/src/ServiceStack/MiniProfiler/Data


cor*_*ews 1

@aghilas 的答案是使用其他一些库,但足以指出我之前似乎无法弄清楚的错误。

我最终不得不从使用 SqlConnection 更改为使用 DbConnection,对于 SQLCommand => DbCommand 和 SQLDataReader => DbDataReader 也是如此。这使得 ProfiledDbConnection 能够正确连接。

...
using StackExchange.Profiling;
using StackExchange.Profiling.Data;
...
using( DbConnection conn = new ProfiledDbConnection( new SqlConnection( ConnectionString ), MiniProfiler.Current ) ) {
        using( DbCommand command = conn.CreateCommand() ) {
            command.CommandText = CommandText;
            command.Connection = conn;
            command.CommandType = SQLCommandType;
            foreach( SqlParameter p in ParamsToAdd ) {
                command.Parameters.Add( p );
            }
            conn.Open();
            DbDataReader rdr;
            try {
                rdr = command.ExecuteReader();
            } catch( Exception ex ) {
                //log error
            }
            using( rdr ) {
                while( rdr.Read() ) {
                    yield return (IDataRecord)rdr;
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)