Why am I getting InvalidCastException when casting object to integer?

血红的双手。 提交于 2019-12-11 12:43:16

问题


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

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

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 is hitting the following sproc:

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

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

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

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


回答1:


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

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



来源:https://stackoverflow.com/questions/1512661/why-am-i-getting-invalidcastexception-when-casting-object-to-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!