1

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?

Giles Roberts
  • 6,407
  • 6
  • 48
  • 63

1 Answers1

1

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks a lot. So a second question if you're kind... The mini profiler is advertised as working with SqlConnection and I've got a bunch of legacy code I'm trying to profile. Full of SqlCommands etc. What is the recommended way to profile this code? – Giles Roberts Apr 30 '13 at 15:49
  • 1
    @GilesRoberts: As I said in the answer, "It's not clear to me from the MiniProfiler documentation how you're meant to use a `ProfiledDbConnection` with a `SqlCommand`." I've never used MiniProfiler myself. – Jon Skeet Apr 30 '13 at 15:50