Search code examples
c#datetimedbnull

Handling a DateTime DBNull


I have seen many, many versions of this on SO, but none of them seem to quite work for my needs.

My data comes from a vendor database that allows null for DateTime fields. First I pull my data into a DataTable.

using (SqlCommand cmd = new SqlCommand(sb.ToString(), conn))
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
    da.Fill(dt);
}

I am converting a DataTable to a List<> for processing.

var equipment = from i in dt.AsEnumerable()
    select new Equipment()
    {
        Id = i.Field<string>("ID"),
        BeginDate = i.Field<DateTime>("BeginDate"),
        EndDate = i.Field<DateTime>("EndDate"),
        EstimatedLife = i.Field<double>("EstimatedLife")
    }

So, how do I check for DBNull in this instance? I tried to write a method.

    public DateTime CheckDBNull(object dateTime)
    {
        if (dateTime == DBNull.Value)
            return DateTime.MinValue;
        else
            return (DateTime)dateTime;
    }

Solution

  • One possible option is store it as a nullable date time with the syntax DateTime?

    Here is a link to the MSDN about using nullable types