Handling a DateTime DBNull
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.
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
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:
IDataRecord record = FromSomeSqlQuerySource;
string nullableString;
DateTime? nullableDateTime;
nullableString = record["StringFromRecord"] as string;
nullableDateTime = record["DateTimeFromRecord"] as DateTime?;