Sarfaraz Makandar
Sarfaraz Makandar

Reputation: 6733

Specified cast is not valid in C#

I have a column which is of type bigint in the database table. I want it to retrieve and assign it to variable in C# as shown below in the example.

Example:

obj.Total1 = (Int32)reader["Slno"] != null ? (Int32)reader["Slno"] : 0;
obj.Total2 = (Int32)reader["Rlno"] != null ? (Int32)reader["Rlno"] : 0;

Note: Here Slno and Rlno are of type bigint in database table.

Error: Following is the error message.

Specified cast is not valid.

Upvotes: 1

Views: 2403

Answers (3)

In my case I was getting a "specified cast is not valid", when my table was empty.

so I changed my code like so:

while (reader.Read())
    max = reader.GetInt32(0);

Added a check for DBNull:

while (reader.Read())
    max = reader.IsDBNull(0) ? 0 : reader.GetInt32(0);

Upvotes: 1

Trevor Pilley
Trevor Pilley

Reputation: 16393

BigInt needs to be mapped to long which is the equivalent 64bit integer value in C#.

Also, you should alter your code to something like this:

int slnoCol = reader.GetOrdinal("Slno");
int rlnoCol = reader.GetOrdinal("Rlno");

obj.Total1 = !reader.IsDBNull(slnoCol) ? reader.GetInt64(slnoCol) : (long)0;
obj.Total2 = !reader.IsDBNull(rlnoCol) ? reader.GetInt64(rlnoCol) : (long)0;

EDIT:

After noticing your comment that Total1 and Total2 are int, you also need to change them to long

public long Total1 { get; set; }
public long Total2 { get; set; }

This is because int is a 32bit integer which cannot store the same max value as a 64bit integer which is what you are using in your table.

Upvotes: 2

dcastro
dcastro

Reputation: 68660

SQL's BigInt maps to a long in C#, not an int.

Upvotes: 5

Related Questions