Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime2 to C# DateTime with SqlDataReader

I realize this might be a dupe, but I've spent hours searching for the answer and can't seem to find it.

I'm currently creating a web API that retrieves concert data.

I have a SQL Server table that holds a start and end date, both as a datetime2 type. I've inserted the dates in this format and they don't cause any problems when viewing the database:

2015-10-08T20:00:00.0000000+01:00

My model:

public class Concert
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int LocationId { get; set; }

    [Column(TypeName = "DateTime2")]
    public DateTime Start { get; set; }

    [Column(TypeName = "DateTime2")]
    public DateTime End { get; set; }

    public string Description { get; set; }
    public string Url { get; set; }
}

And my method in the class that brings up my database data:

    public List<Concert> getAll() 
    {
        List<Concert> concerts = new List<Concert>();

        SqlConnection connection = CasWebAPIdb.getConnection();
        String selectAll = "SELECT ConcertId, ConcertName, ConcertLocationId FROM dbo.Concerts";
        SqlCommand selectCommand = new SqlCommand(selectAll, connection);

        try
        {
            connection.Open();
            SqlDataReader reader = selectCommand.ExecuteReader();
            var isoDateTimeFormat = CultureInfo.InvariantCulture.DateTimeFormat;

            while (reader.Read())
            {
                //Debug.WriteLine("lol: " + reader["ConcertEnd"].GetType());

                Concert concert = new Concert();

                concert.Id = (int)reader["ConcertId"];
                concert.Name = reader["ConcertName"].ToString();
                concert.LocationId = (int)reader["ConcertLocationId"];
                concert.Start = (DateTime)reader["ConcertStart"];
                concert.End = (DateTime)reader["ConcertEnd"];

                concerts.Add(concert);
            }
        }
        catch (SqlException ex)
        {
            throw ex;
        }
        finally
        {
            connection.Close();
        }
        return concerts;
    }
}

I get this error when debugging:

An exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll but was not handled in user code

I have tried a lot of things and followed a lot of examples and codes, but I can't seem to convert this properly. Does anybody have an idea?

solution

I forgot to add the 'concertStart' and 'concertEnd' to my query. Problem solved, thanks!

like image 227
Dennie Avatar asked Feb 28 '15 10:02

Dennie


People also ask

What is DateTime2 format?

The DateTime2 is an SQL Server data type, that stores both date & time together. The time is based on the 24 hours clock. The DateTime2 stores the fractional seconds Up to 7 decimal places (1⁄10000000 of a second). The Precision is optional and you can specify it while defining the DateTime2 column.

What is DateTime2 datatype?

Defines a date that is combined with a time of day that is based on 24-hour clock. datetime2 can be considered as an extension of the existing datetime type that has a larger date range, a larger default fractional precision, and optional user-specified precision.

Should I use DateTime2?

Microsoft recommends using DateTime2 instead of DateTime as it is more portable and provides more seconds precision. Also, DateTime2 has a larger date range and optional user-defined seconds precision with higher accuracy.

Should I use DateTime2 or Datetimeoffset?

If you are storing only UTC values (where the offset is always zero), you can save storage space with datetime2 . datetimeoffset requires 10 bytes of storage whereas datetime needs 8 bytes for precision 5 or greater, 7 bytes for precision 3-4, and 6 bytes for precision 2 or less.


Video Answer


2 Answers

First of all, if you want to read the value of ConcertStart and ConcertEnd, you'd have to include them in your SELECT!!$

string selectAll = @"SELECT ConcertId, ConcertName, ConcertLocationId,
                            ConcertStart, ConcertEnd     <<--- add these!! 
                     FROM dbo.Concerts";

Try this:

while (reader.Read())
{
    Concert concert = new Concert();

    concert.Id = (int)reader["ConcertId"];
    concert.Name = reader["ConcertName"].ToString();
    concert.LocationId = (int)reader["ConcertLocationId"];
    concert.Start = reader.GetFieldValue<DateTime>(reader.GetOrdinal("ConcertStart"));
    concert.End = reader.GetFieldValue<DateTime>(reader.GetOrdinal("ConcertEnd"));

    concerts.Add(concert);
}

I have no trouble at all reading out a DATETIME2(3) value from the SQL Server database using

reader.GetFieldValue<DateTime>(reader.GetOrdinal("ConcertEnd"));

Does that work for you?

like image 177
marc_s Avatar answered Oct 08 '22 19:10

marc_s


The problem is that in your select, you only return 3 of the columns needed:

 String selectAll = "SELECT ConcertId, ConcertName, ConcertLocationId ...";

Whereas in your reader, you attempt to scrape 5 columns:

concert.Id = (int)reader["ConcertId"];
concert.Name = reader["ConcertName"].ToString();
concert.LocationId = (int)reader["ConcertLocationId"];
concert.Start = (DateTime)reader["ConcertStart"];
concert.End = (DateTime)reader["ConcertEnd"];

Hence the IndexOutOfRangeException. Either select all columns, or remove the extraneous ones from the reader.

The issue isn't related to Sql DateTime2 vs .Net DateTime - ADO will bind these just fine.

like image 24
StuartLC Avatar answered Oct 08 '22 19:10

StuartLC