2012-03-01 104 views
2

我遇到以下錯誤消息,我正在使用petaPOCO。爲什麼我在此錯誤消息,什麼我做錯了有這個消息:找不到異常消息

{"There is already an open DataReader associated with this Command which must be closed first."} 

This is what I have been able to copy for the exception message. 

System.InvalidOperationException了抓 消息=已經有一個與此相關聯的打開的DataReader必須先關閉的命令。 源= System.Data 堆棧跟蹤: 在System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand的命令) 在System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(字符串方法,SqlCommand的命令) 在System.Data.SqlClient的。 SqlCommand.ValidateCommand(String method,Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior,RunBehavior runBehavior,Boolean returnStream,String method,DbAsyncResult result) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior,RunBehavior runBehavior,Boolean returnStream,String方法) at System.Data.SqlClient.SqlCommand.ExecuteScalar() at PetaPoco.Databas e.Insert(字符串表名,字符串primaryKeyName,布爾自動增量,對象POCO)在C:\開發\代碼\ API \模型\ PetaPoco.cs:線1243 的InnerException:

+1

顯示正在使用DataReader的代碼 – Andy 2012-03-01 07:01:33

+1

您使用的是db.Query方法嗎? – patmortech 2012-03-01 11:12:20

+0

請添加一些數據訪問邏輯代碼。 – 2012-03-06 08:36:31

回答

4
這裏

是一個很好的解釋爲什麼本引發異常:

http://blogs.msdn.com/b/spike/archive/2009/08/20/there-is-already-an-open-datareader-associated-with-this-command-which-must-be-closed-first-explained.aspx

的結論是如下:

因爲SqlDataReader的保持內存流(結果集)可用,直到明確關閉SqlDataReader中,你可以得到,如果你這個異常嘗試創建一個新的閱讀器而不關閉前一個閱讀器。

改變你的代碼有一個using語句當你創建一個SqlDataReader:

SqlCommand cmd = new SqlCommand(sql, con); 
using (SqlDataReader rdr = cmd.ExecuteReader()) 
{ 
    while (rdr.Read()) 
    { 
    Console.WriteLine("cid: {0}, ctext: {1}", rdr[0].ToString(), rdr[1].ToString()); 
    } 
} 

使用會自動調用Dispose()(這將關閉reader)關閉(截止})當達到。

如果在petaPOCO中引發此異常,那麼它們的代碼中存在一個錯誤,或者您以未指定的方式使用代碼。

4

您的ORM(或ORM的使用模式)期望基礎ADO.NET提供程序允許在單個連接上使用多個打開的DataReader。您似乎使用的SQL Server Provider可以這樣做,但您必須將MultipleActiveResultSets=True添加到用於連接到數據庫的連接字符串中。

10

我知道這是舊的,但我想添加一些東西,可以幫助下一個人搜索這個。如果您使用查詢方法,則會發生此錯誤。查詢方法不會加載內存中的所有內容。如果您需要加載並關閉連接,則需要使用Fetch。

這是從網站:

查詢VS取

數據庫類有檢索記錄查詢和 取兩種方法。除非Fetch返回POCO的列表<> ,而Query使用收益率返回遍歷結果 ,而不將整個集合加載到內存中,否則這幾乎完全相同。

希望這可以幫助別人。

+0

謝謝,它花了我一個小時才找到您的解決方案 – 2013-09-12 13:42:00

+0

謝謝,提示。新PetaPOCO的答案部分正確。我想現在Fetch也會調用Query。修復它的更好方法是調用'ToList()'或類似的方法來獲取完整的數據集並關閉閱讀器。 – Chandermani 2014-03-26 09:04:23

0

如果您的poco沒有公共或受保護可見性的無參數構造函數,則也可以在PetaPoco中引發此異常。