为什么我会收到InvalidCastException的铸造对象时的整数? [英] Why am I getting InvalidCastException when casting object to integer?

查看:109
本文介绍了为什么我会收到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从我的code,它返回一个对象,然后我试图铸造的对象为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) {...}

,但是这并不重要)。

, but that's not as important).

的ExecuteScalar打着以下存储过程:

ExecuteScalar is hitting the following sproc:

...  
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变量,并从存储过程返回之前分配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!)

所以你的code的努力蒙上了BIGINT为int。

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

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

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