views:

51

answers:

3

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

Use

Converter.IsDBNull(value);

or in case of use of SqlDataReader

reader.IsDBNull(ordinal);

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

abatishchev
+6  A: 

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

Scott Chamberlain
So on my Equipment object define the `DateTime` fields as `DateTime?`
Mike Wills
If it is a valid business case for your Equipment to not have a begin or end date then yes. Otherwise your db layer should throw an exception.
vc 74
yep - it's a shortcut for `Nullable<DateTime>`
Rob Fonseca-Ensor
A: 

here is an example of some code i use to read Datetimes

im sure it could be written better but runs fine for me

   public DateTime? ReadNullableDateTimefromReader(string field, IDataRecord data)
    {

        var a = data[field];
        if (a != DBNull.Value)
        {
            return Convert.ToDateTime(a);
        }
        return null;
    }

    public DateTime ReadDateTimefromReader(string field, IDataRecord data)
    {
        DateTime value;
        var valueAsString = data[field].ToString();
        try
        {
            value = DateTime.Parse(valueAsString);
        }
        catch (Exception)
        {
            throw new Exception("Cannot read Datetime from reader");
        }

        return value;
    }
Yakyb