Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable DateTime and the Database

I've got a nullable datetime object in C#.

DateTime? StartDate = new DateTime();

I then check a user submitted value to determine if a date is applicable to this record:

if (Complete == "N/A")
{
    StartDate = null;
}

Now I come to my query which may or may not be inserting a null datetime:

using (SqlCommand command = new SqlCommand(updateSql, db))
{
    command.Parameters.Add("@Date_Started", SqlDbType.DateTime).Value = StartDate;
}

As you'd probably expect if the start date is null then I get an error that the type is not correct. What's the best way to proceed from here?

I have considered checking startdate is null but am not sure how to do that when the type is nullable.

like image 891
deed02392 Avatar asked Feb 01 '12 16:02

deed02392


2 Answers

This will pass a database NULL value as the parameter if StartDate is null:

using (SqlCommand command = new SqlCommand(updateSql, db))
{
    command.Parameters.Add("@Date_Started", SqlDbType.DateTime).Value = (object)StartDate ?? DBNull.Value;
}
like image 51
Roy Goode Avatar answered Sep 28 '22 05:09

Roy Goode


using (SqlCommand command = new SqlCommand(updateSql, db))
{
    if (StartDate.HasValue())
        command.Parameters.Add("@Date_Started", SqlDbType.DateTime).Value
            = StartDate;
    else
        command.Parameters.Add("@Date_Started", SqlDbType.DateTime).Value 
            = DBNull.Value;
}
like image 29
Dennis Traub Avatar answered Sep 28 '22 03:09

Dennis Traub