2012-02-24 96 views
1

我不确定这是否可能,但只是需要解决当前问题。 我有一个数据层的方法,它返回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; 
} 

如果问题不清楚,请让我知道。

+0

是代码你有吗?您已经完成了读取结果(除非您有存储过程返回的多个结果集),为什么不关闭读取器并获取OUT参数值呢? – alwayslearning 2012-02-25 00:21:50

回答

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 
      } 
     } 
+0

我知道我的代码并不擅长设计本身。但这就是我必须努力的。 @SergeyG:我认为我们的代码几乎是相似的。对你起作用吗? – PraveenLearnsEveryday 2012-07-31 11:50:53

相关问题