OracleDataReader。错误:操作无效。连接已关闭

时间:2014-03-31 03:24:28

标签: c# datareader

从Oracle DB获取内容时遇到错误。

这是我的代码:

public virtual IDataReader LoadDataReaderWithSqlString(string strQuery, ISessionScope session)
    {
        var s = GetSession(session);
        using (var connection = s.Connection)
        {
            var command = connection.CreateCommand();
            command.Connection = connection;
            if (connection.State == ConnectionState.Closed || connection.State == ConnectionState.Broken)
                connection.Open();
            command.CommandType = CommandType.Text;
            command.CommandText = s.CreateSQLQuery(strQuery).ToString();
            s.Transaction.Enlist(command); // Set the command to exeute using the NHibernate's transaction
            using (var dataReader = command.ExecuteReader())
            {
                if(dataReader.Read())
                    return dataReader;
            }
        }
        return null;
    }

当我调试时,我能够在dataReader中看到返回值。 我使用NHibernate来运行Raw SQL。我想返回DataReader。有人可以帮我吗?

2 个答案:

答案 0 :(得分:3)

您是否正在尝试返回已打开的IDataReader?问题是您将ExecuteReader包裹在using语句中。 using表示在执行dataReader内的代码后,您的using将被处理掉。所以你返回处置对象。解决方案是:删除using

var dataReader = command.ExecuteReader();
if(dataReader.Read())
    return dataReader;

对于连接对象也一样。

添加

正如David在评论中提到的那样,您可能希望避免资源泄漏(我的意思是在打开连接但未执行命令的情况下),那么您应该处理这样的异常:

public virtual IDataReader LoadDataReaderWithSqlString(string strQuery, ISessionScope session)
{
    try 
    {
        var s = GetSession(session);
        var connection = s.Connection;

        var command = connection.CreateCommand();
        command.Connection = connection;
        if (connection.State == ConnectionState.Closed || connection.State == ConnectionState.Broken)
            connection.Open();

        command.CommandType = CommandType.Text;
        command.CommandText = s.CreateSQLQuery(strQuery).ToString();
        s.Transaction.Enlist(command); // Set the command to exeute using the NHibernate's transaction

        try
        {
            var dataReader = command.ExecuteReader();
            if(dataReader.Read())
                return dataReader;
        }
        catch (DbException)
        { 
            // error executing command
            connection.Close();
            return null; // or throw; // it depends on your logic
        }
    }
    catch (DbException)
    {
        // if connection was not opened
        return null; // or throw; // it depends on your logic
    }
    return null;
}

答案 1 :(得分:0)

那是因为你有

using (var connection = s.Connection)using (var dataReader = command.ExecuteReader())

using阻止将处置对象(此处connectiondataReader

如果您需要返回dataReader

,请删除使用块