Nullable DateTime and the Database

deed02392 picture deed02392 · Feb 1, 2012 · Viewed 8k times · Source

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.

Answer

Roy Goode picture Roy Goode · Feb 1, 2012

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