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;
}
I wrote a generic extension method that I use in all of my projects:
Usage example:
Use
IsDBNull()
or if you have a
SqlDataReader
And make your
DateTime
properties to be nullable (DateTime?
) and setnull
in case ofDBNull
.Field<T>()
will automatically do this.You should use
DataRow["ColumnName"] is DBNull
to compare DateTime null.E.g.:
I have found that the easiest way to handle this is to cast the field as your data type using the "as" keyword. This works great for database fields that can be null, and is nice and simple.
Here is more detail on this: Direct casting vs 'as' operator?
Example:
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
here is an example of some code i use to read Datetimes
im sure it could be written better but runs fine for me