Search code examples
c#sqlsql-servernulldbnull

invalid cast exception when trying to transform SQL int -> c# int?


Hi I'm currently using the following to get the columns of a sql server database

public IDataReader myReader()
{
    DbCommand = new SqlCommand("Select * from Mydatabase");
    SqlConnection con = new SqlConnection(connectionstr);
    con.Open();
    DbCommand.Connection = con
    return command.ExecuteReader(CommandBehavior.closeConnection);
}

IDataReader reader = myReader();
while (reader.Read())
{
    int? a = (int?)reader["myIntColumn"];
}

At other locations (for other tables) the code works fine and also for this table it works fine until I come to the fields that are int in the database. Then I get System.InvalidCastException (in other tables I didn't get that problem).

Is there anything I did wrong? Or that I have to do to make this work? (the int value in question is NULL in the DB)


Solution

  • Your code will not work when the result is null, since the value of the column will be DbNull.Value on the .NET side then.

    Try this:

    int? a = reader["myIntColumn"] as int?;