CASTING ADO.NET DATAREADER TO IDATARECORD GIVING STRANGE RESULT

Madam Walker

Total Post:22

Points:154
Posted by  Madam Walker
 2705  View(s)
Ratings:
Rate this:
Hi Expert, 

I have a query that I run against the database, and I can see that there is a record for 31/05/2013. When I run this query from C# with ADO.NET, and then use the following code, I am missing the record for 31/05/2013

var timeSeriesList = new List<TimeSeries>();  
using (var reader = cmd.ExecuteReader())
{
    while (reader.Read())
    {
        timeSeriesList = reader.Cast<IDataRecord>()
            .Select(r => new TimeSeries
                 {
                     MidRate = (double)r["MidRate"],
                     RiskFactorName = (string)r["RiskFactorName"],
                     SeriesDate = (DateTime)r["SeriesDate"]
                 }).ToList();
    }
}

However, if I use the same query with this code:

var timeSeriesList = new List<TimeSeries>();                        
using (var reader = cmd.ExecuteReader())
{
    while (reader.Read())
    {
        var timeSeries = new TimeSeries
                 {
                     MidRate = (double)reader["MidRate"],
                     RiskFactorName = (string)reader["RiskFactorName"],
                     SeriesDate = (DateTime)reader["SeriesDate"]
                 };
        timeSeriesList.Add(timeSeries);
    }
}

...then the record at 31/05/2013 is in the collection - why would the first block of code give this result?

  1. Sumit Kesarwani

    Post:378

    Points:2694
    Re: Casting Ado.net DataReader to IDataRecord giving strange result

    Hi,


    I think that you are missing record in first example because you move reader by one and then cast it.

    Try this change and see if it worked:

    var timeSeries = new List<TimeSeries>();  
    using (var reader = cmd.ExecuteReader())
    {
        if (reader.HasRows)
        {
            timeSeries = reader.Cast<IDataRecord>()
                .Select(r => new TimeSeries
                     {
                         MidRate = (double)r["MidRate"],
                         RiskFactorName = (string)r["RiskFactorName"],
                         SeriesDate = (DateTime)r["SeriesDate"]
                     }).ToList();
        }
    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!