2012-02-24 6 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

答えて

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

関連する問題