2013-04-30 53 views
0

我收到錯誤「連接屬性尚未初始化」用下面的代碼尚未初始化:連接使用的SqlCommand時有迷你探查

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(); 

當它到達Command.ExecuteReader卻() ;線。

如果刪除行

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

然後代碼工作正常。什麼是造成我的執行讀者拋出錯誤的配置數據庫連接?

回答

1

什麼是造成我的執行讀者拋出錯誤的配置數據庫連接?

那麼在創建ProfiledDbConnection後,它不再是SqlConnection了,是嗎?所以這條線:

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

是有效的:

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

...不執行該查詢的好兆頭。這就是爲什麼無條件地使用as是一個壞主意 - 如果您使用了一個強制轉換表達式,那麼會拋出一個更有用的異常。

從MiniProfiler文檔中我不清楚你是如何使用ProfiledDbConnectionSqlCommand。您很可能想用ProfiledDbCommand代替。

+0

非常感謝。所以,第二個問題,如果你是親切的...迷你Profiler廣告宣傳與SqlConnection一起工作,我有一堆遺傳代碼,我試圖分析。完整的SqlCommands等什麼是推薦的方式來分析此代碼? – 2013-04-30 15:49:04

+1

@GilesRoberts:正如我在答案中所說的那樣,「從MiniProfiler文檔中我不清楚你是如何使用'ProfiledDbConnection'和'SqlCommand'。」我從未使用過MiniProfiler。 – 2013-04-30 15:50:18