2012-03-01 224 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中引发此异常。