我有以下错误消息,我正在使用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,必须先关闭它 . Source = System.Data StackTrace:System.Data.SqlClient上的System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand命令)处于System.Data.SqlClient.SqlCommand.ValidateCommand的System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method,SqlCommand命令)处 . System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior,RunBehavior runBehavior,Boolean returnStream)中System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior,RunBehavior runBehavior,Boolean returnStream,String方法,DbAsyncResult结果)的方法,布尔异步) ,String方法)在C:\ Dev \ Code \ API \ Models \ PetaPoco.cs中的PetaPoco.Database.Insert(String tableName,String primaryKeyName,Boolean autoIncrement,Object poco)中的System.Data.SqlClient.SqlCommand.ExecuteScalar()处:第1243行InnerException:
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,如果您尝试创建新的读取器而不关闭前一个读取器,则可以获得此异常 .
每当您创建SqlDataReader时,请更改代码以使用using语句:
当达到闭包(结束})时,使用将自动调用dispose()(关闭阅读器) .
如果在petaPOCO中引发此异常,则代码中存在错误,或者您以未指定的方式使用代码 .
我知道这是旧的,但我想添加一些可能有助于下一个人搜索此内容的东西 . 如果使用Query方法,则会发生此错误 . Query方法不会将所有内容加载到内存中 . 如果需要加载它然后关闭连接,则需要使用Fetch .
这是来自网站:
希望这有助于其他人 .
您的ORM(或ORM的使用模式)希望底层ADO.NET提供程序允许在单个Connection上使用多个打开的DataReader . 您似乎使用的SQL Server提供程序可以这样做,但您必须将
MultipleActiveResultSets=True
添加到用于连接到数据库的连接字符串 .如果您的poco没有公共或受保护可见性的无参数构造函数,也可以在PetaPoco中抛出此异常 .