Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataReader: Specified cast is not valid (Int32)

Why does SqlDataReader throw an exception when converting 0 to integer?

?dataReader(3)
0 {Short}
    Short: 0
?dataReader.GetInt16(3)
0
?dataReader.GetInt32(3)
{"Specified cast is not valid."}
    _HResult: -2147467262
    _message: "Specified cast is not valid."
    Data: {System.Collections.ListDictionaryInternal}
    HelpLink: Nothing
    HResult: -2147467262
    InnerException: Nothing
    IsTransient: False
    Message: "Specified cast is not valid."
    Source: "System.Data"
    StackTrace: "   at System.Data.SqlClient.SqlBuffer.get_Int32()     
                    at System.Data.SqlClient.SqlDataReader.GetInt32(Int32 i)"
    TargetSite: {Int32 get_Int32()}
like image 425
moldovanu Avatar asked Apr 12 '12 07:04

moldovanu


1 Answers

It isn't a convert - it is a cast. The same as:

short x = 0;
object y = x;
int z = (int)y; // BOOM! InvalidCastException Specified cast is not valid.

In both cases, a short is not an int.

If unsure of the type, you might try:

int i = Convert.ToInt32(dataReader.GetValue(3));
like image 133
Marc Gravell Avatar answered Sep 18 '22 13:09

Marc Gravell