为什么当将对象转换为整型时会出现InvalidCastException? [英] Why am I getting InvalidCastException when casting object to integer?

查看:151
本文介绍了为什么当将对象转换为整型时会出现InvalidCastException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题,这是设置:

I had an odd problem, here's the setup:

ASP.NET 3.5应用程序/ MSSQLSERVER 2008后端。

ASP.NET 3.5 app / MSSQLSERVER 2008 back-end.

我从我的代码中调用ExecuteScalar,它返回了一个对象,然后我尝试将该对象转换为int(我实际上有一个通用方法

I called ExecuteScalar from my code, which returned an object, then I tried casting that object to int (i actually have a generic method

 T ConvertDBValue<T>(object o) {...}

ExecuteScalar is hitting the following sproc:

$ c> ...
insert into ...
select scope_identity()

... insert into ... select scope_identity()

我的主键是一个身份字段,并返回85.接下来的事情是InvalidCastException试图将85转换为int。

My primary key is an identity field, and returned 85. Next thing I got is InvalidCastException trying to cast 85 to int.

解决方案是明确创建一个INT变量,并在从sproc返回之前将SCOPE_IDENTITY()赋值给它:

The solution was to explicitly create an INT variable, and assign SCOPE_IDENTITY() to it before returning it from the sproc as follows:

...  
DECLARE @x int
insert into ...
select @x = scope_identity()
select @x

有人可以告诉我第一种方法的问题是什么,为什么不将85转换为int?

Can somebody tell me what was the problem with my first approach, and why wouldn't it cast 85 to int?

推荐答案

scope_identity() 实际上返回了一个(TSQL) BIGINT (我已经被这个捕获了!)

scope_identity() actually returns a (TSQL) BIGINT (I've been caught by this before!)

所以你的代码试图将BIGINT转换为int。

So your code was trying to cast a BIGINT to an int.

这篇关于为什么当将对象转换为整型时会出现InvalidCastException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆