2012-02-21 409 views
3

嗨我试图从方法返回DataReader,但它返回一个关闭的DbDataReader对象。任何想法来解决这个问题。我愿意提供更好的代码。DbDataReader错误:读取器关闭时尝试调用无效

感谢

UPDATE 我不想离开数据库连接打开。有什么办法可以在关闭连接后返回打开的DataReader。

internal DbDataReader ExecuteReader(SqlCommand command, CommandBehavior behavior, string connectionString) 
    { 
    DbDataReader dataReader = null; 
    try 
    { 
     SqlConnection connection = GetConnection(connectionString); 
     Open(connection); 
     command.Connection = connection; 
     command.CommandTimeout = 60; 
     dataReader = command.ExecuteReader(behavior); 
     Close(connection); 
    } 
    catch 
    { 
    } 
    return dataReader; 
} 
+0

如果你在'return dataReader;'上放置了一个断点,它在这一点上是否关闭? – 2012-02-21 16:39:26

+0

嗨@NeilKnight,是它在那个时候关闭了 – Scorpion 2012-02-21 16:42:45

+0

你可能还想考虑一下你的空catch块。你当然不想吞下所有的例外,是吗? – 2012-02-21 16:55:11

回答

6

它因为关闭了数据库连接而关闭。它无法从关闭的SqlConnection中读取数据。如果要重新使用连接,可以将Open连接传递给方法,并在从DbDataReader中使用数据后关闭连接。

+0

嗨@Adriano,如果我离开连接打开它会是一个问题? – Scorpion 2012-02-21 16:49:56

+2

您必须尽快关闭连接(服务器的连接是有限的资源),即使它稍后将由垃圾收集器释放。这不会**意味着你必须立即关闭连接**,花时间消耗数据,然后关闭连接。 – 2012-02-21 17:03:18

相关问题