Search code examples
c#sqlcommandmvc-mini-profiler

Connection has not been initialized when using SqlCommand with mini profiler


I'm receiving the error "Connection property has not been initialized" with the following code:

DbConnection connection = new SqlConnection(connStr);
connection.Open();
connection = new StackExchange.Profiling.Data.ProfiledDbConnection(connection, MiniProfiler.Current);
SqlCommand command = new SqlCommand("GetLanguages", connection as SqlConnection);
command.CommandType = CommandType.StoredProcedure;
command.CommandTimeout = 240;
command.ExecuteReader();

when it gets to the command.ExecuteReader(); line.

If remove the line

connection = new StackExchange.Profiling.Data.ProfiledDbConnection(connection, MiniProfiler.Current);

then the code works fine. What is it about the profiled db connection that is causing my execute reader to throw the error?


Solution

  • What is it about the profiled db connection that is causing my execute reader to throw the error?

    Well after creating a ProfiledDbConnection, it's no longer a SqlConnection, is it? So this line:

    SqlCommand command = new SqlCommand("GetLanguages", connection as SqlConnection);
    

    is effectively:

    SqlCommand command = new SqlCommand("GetLanguages", null);
    

    ... which doesn't bode well for executing the query. This is why using as unconditionally is a bad idea - if you'd used a cast expression instead, a more useful exception would have been thrown.

    It's not clear to me from the MiniProfiler documentation how you're meant to use a ProfiledDbConnection with a SqlCommand. You quite possibly want to use ProfiledDbCommand instead.