简体   繁体   English

如何在Visual C#中使用DataReader处理多个结果?

[英]How to handle Multiple Results by Using the DataReader in Visual C#?

I have a stored procedure which returns two tables. 我有一个存储过程返回两个表。 Table 1 has for example {1,2,3,4,5}, the table 2 will have have {a,b,c,d,e}. 表1例如具有{1,2,3,4,5},表2将具有{a,b,c,d,e}。 For example {1,a}, {2,b} similarly all are related. 例如,{1,a},{2,b}都相似。

In my reader, I have to read all these data into a List. 在阅读器中,我必须将所有这些数据读入一个列表。 Object will have have two properties where {1,a} go. 对象将在{1,a}处具有两个属性。 This is the code I have now, 这是我现在拥有的代码

while(reader.Read())
        {
            Transaction transaction = null;
            transactions.Add(transaction = new Transaction()
            {
                TranID = reader.GetInt64(reader.GetOrdinal("TranID"))
            });

            if (reader.NextResult())
            {
                while (reader.Read())
                {
                    transaction.Amounts.Add(new Fund
                    {
                        Amount = reader.GetDecimal(reader.GetOrdinal("Amount")),
                    });
                }
            }
        }

What's happening here is if I return 10 Transaction Ids and 10 Amounts, my final result has only 1 Transaction and 10 Amounts mapped to it. 这里发生的是,如果我返回10个交易ID和10个金额,我的最终结果只有1个交易和10个金额映射到它。 How do I get 10 Transactions with equivalent Amount? 如何获得10个等值金额的交易?

You can not access multiple resultsets this way from SqlDataReader. 您不能通过这种方式从SqlDataReader访问多个结果集。 You can access all the rows from one resultset at a time. 您可以一次从一个结果集中访问所有行。 If you move to the nextresult set, you can not go back to the previous result set. 如果移至下一个结果集,则无法返回到上一个结果集。

Following is the sample code of how you retrieve data from multiple resultsets of SqlDataReader. 以下是如何从SqlDataReader的多个结果集中检索数据的示例代码。

while (reader.Read())
{
     Console.WriteLine(reader.GetString(0));
}

if (reader.NextResult())
{
    while (reader.Read())
    {
        Console.WriteLine(reader.GetString(0));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM