I have a class with a field named myDateTime
typed as nullable DateTime
, these are the accessor methods:
System.DateTime? _MyDateTime;
public System.DateTime? MyDateTime {get; set;}
Somewhere else in my code I need to value MyDateTime
attribute with the data write inside myColumn
.
MyDateTime = Convert.ToDateTime(myReader["myColumn"]);
The value from myColumn
can be NULL
or DateTime
. Alas if myColumn
is NULL this code produce an error cause I can't convert a NULL value. Further, I can't write:
MyDateTime = System.DBNull.Value;
So I don't know how I could handle this issue if NULL
value is present in that field.
I would avoid the use of a simple object to store the data and I would preserve a sort of attributes typing.
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...)
See more on this question at Stackoverflow