I start MySQL query going to a list with one value that is a DateTime object. As this list builds it hits a null value and — DateTimeSqlNullValueException: Data is Null.
First I naively tried using ISNULL, !=NULL, ==NULL… which are not methods of the DateTime object. Then I tried
queryResult.EventTime = rdr.GetDateTime("timeIn");
if (Convert.IsDBNull(rdr.GetDateTime("timeIn")))
{
Console.Write("yeup it's null");
queryResult2.EventTime = DateTime.MinValue;
}
This didn’t work either.
Then I though instead of rdr.GetDateTime() I thought maybe using GetString() instead and use the methods for strings to test for null then change it back to a DateTime and set it to DateTime.MinValueso I could address it in the view later on. This seemed like a total cludge and not very elegant. So I have been searching for the one liner that I can test the nullness of rdr.GetDateTime("timeIn"); and set it to DateTime.MinValue
you can write an extension method which will do the check and so make it a one liner (untested code, but should give you the idea):
you can then call this like so:
you don’t need to pass in the default value, but its a good idea to do so, as you then have control from the calling site to specify the value you want if the database field is null, and the calling site is where you will know what value you want. you may not always want
DateTime.MinValue, you may wantDateTime.Nowsometimes for example