Home > DeveloperSection > Forums > Casting Ado.net DataReader to IDataRecord giving strange result
Madam Walker
Madam Walker

Total Post:22

Points:154
Posted on    June-19-2013 3:47 AM

 ADO.Net ADO.Net 
Ratings:


 1 Reply(s)
 2113  View(s)
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?



Sumit Kesarwani

Total Post:378

Points:2694
Posted on    June-19-2013 8:41 AM

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();
    }
}

Don't want to miss updates? Please click the below button!

Follow MindStick