在不关闭datareader的情况下读取输出参数

时间:2012-02-24 15:02:20

标签: ado.net

我不确定这是否可能,但只需要解决我当前的问题。 我在Data层中有一个返回SqlDataReader对象的方法。这稍后由业务层调用。

public SqlDataReader GetAll(out int count)
{
    using (SqlConnection conn = new SqlConnection())
{
    IDataReader reader = null;
    SqlCommand cmd = new SqlCommand("sproc", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    // add parameters
    SqlParameter outputParam = cmd.Parameters.Add("@Count", SqlDbType.Int);
    outputParam.Direction = ParameterDirection.Output;

    conn.Open();

    reader = cmd.ExecuteReader();
    {
        while(reader.Read())
        {
            //read in data
        }
        **// not possible as the reader is not closed.
        // need to set this out variable here
        count = outputParam.Value; //doesn't work/**

    }

}
return reader;
}

如果问题不明确,请告诉我。

1 个答案:

答案 0 :(得分:0)

请看一下这段代码:

using(SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            SqlCommand command = new SqlCommand("testproc", connection);
            command.CommandType = CommandType.StoredProcedure;

            var countParam = command.CreateParameter();
            countParam.ParameterName = "@TotalCount";
            countParam.Direction = ParameterDirection.Output;
            countParam.DbType = DbType.Int32;
            command.Parameters.Add(countParam);


            using (IDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    Console.Write("exec");
                }

                totalCount = (int)countParam.Value; //totalCount has valid value 
            }
        }