You need to convert from DBNull.Value
to the null value of DateTime?
. It may be simplest to write an extension method on DbDataReader
for that:
public static DateTime? GetNullableDateTime(this DbDataReader reader,
string column)
{
object value = reader[column];
return value == DBNull.Value ? (DateTime?) null : (DateTime) value;
}
Then use it as:
MyDateTime = myReader.GetNullableDateTime("myColumn");
Note that I'm using a cast rather than Convert.ToDateTime
- you could use the latter if you really want to automatically convert from strings to DateTime
values etc, but I prefer to be a bit more explicit about that sort of thing. (It's a sign of the schema probably being inappropriate...)