DbDataReader.GetFieldValue<DateTime> throws casting exception

1.1k views Asked by At

I have this following method:

public static T Get<T>(this DbDataReader reader, int ordinal, Func<T> @default)
{
    if(reader.IsDBNull(ordinal))
        return @default();

    return reader.GetFieldValue<T>(ordinal);
}

When I try to call this with T=DateTime I get the following exception:

System.InvalidCastException was unhandled by user code
  HResult=-2147467262
  Message=Specified cast is not valid.
  Source=System.Data
  StackTrace:
       at System.Data.Common.DbDataReader.GetFieldValue[T](Int32 ordinal)
       ...

The method seems to work fine for other types like strings and numeric types. Does the generic GetFieldValue<T> method simply not work for dates, or have I done something wrong here?


I have fixed it by handling the DateTime case using the specific GetDateTime method instead, but would still like to know if I could get rid of this annoying hack somehow.

public static T Get<T>(this DbDataReader reader, int ordinal, Func<T> @default)
{
   if(reader.IsDBNull(ordinal))
        return @default();

    switch(Type.GetTypeCode(typeof(T)))
    {
        case TypeCode.DateTime:
            return (T)(object)reader.GetDateTime(ordinal);

         default:
            return reader.GetFieldValue<T>(ordinal);
    }
}
0

There are 0 answers