[英]Specified cast is not valid in C#
I have a column which is of type bigint in the database table. 我在数据库表中有一列bigint类型的列。 I want it to retrieve and assign it to variable in C# as shown below in the example.
我希望它检索并将其分配给C#中的变量,如下面的示例所示。
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. 注意 :此处,
Slno
和Rlno
在数据库表中的类型为bigint。
Error : Following is the error message. 错误 :以下是错误消息。
Specified cast is not valid.
SQL的BigInt
映射为C#中的long
,而不是int
。
BigInt needs to be mapped to long
which is the equivalent 64bit integer value in C#. BigInt需要映射为
long
,这是C#中等效的64位整数值。
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
在注意到您的注释Total1和Total2是
int
,您还需要将它们更改为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. 这是因为
int
是一个32位整数,不能与表中使用的64位整数存储相同的最大值。
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
: 添加了对
DBNull
的检查:
while (reader.Read())
max = reader.IsDBNull(0) ? 0 : reader.GetInt32(0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.