Handling a DateTime DBNull

Mike Wills picture Mike Wills · Oct 20, 2010 · Viewed 42.4k times · Source

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

Answer

abatishchev picture abatishchev · Oct 20, 2010

Use IsDBNull()

System.Convert.IsDBNull(value);

or if you have a SqlDataReader

reader.IsDBNull(ordinal);

And make your DateTime properties to be nullable (DateTime?) and set null in case of DBNull. Field<T>() will automatically do this.