System invalidcastexception specified cast is not valid

With the line "cmdThisIDTest = ((int)commandThisID.ExecuteScalar());" in the code listed below I'm acquiring "System.InvalidCastException: Specified cast is not valid." How do I resolve this?

Thanks.

You watching: System invalidcastexception specified cast is not valid

utilizing (var conn = brand-new SqlCeConnection(dbConnectionString))conn.Open();var commandThisID = brand-new SqlCeCommand("SELECT MAX(thisID) FROM table1");commandThisID.Connection = conn;object ThisIDTest = commandThisID.ExecuteScalar();int cmdThisIDTest = 0;if (ThisIDTest != null)cmdThisIDTest = ((int)commandThisID.ExecuteScalar());//END making use of (var conn = brand-new SqlCeConnection(dbConnectionString))
18 comments
share
save
hide
report
62% Upvoted
This thcheck out is archived
New comments cannot be posted and votes cannot be cast
Sort by
best

*

level 1
6 years ago
Also, what are you trying to do? It looks prefer you are trying to gain the last insert ID. Tbelow are much better means then doing a max query.

I bring that up considering that I need to resolve a classical ASP site that has this littered EVERYWHERE.

' Get the last placed ID''set GetID = TrackCon.Execute("SELECT
Identity AS NewID")''set GetID = TrackCon.Execute("SELECT scope_identity() AS NewID")set GetID = TrackCon.Execute("SELECT MAX(AgencyID) AS NewID FROM AgencyInfo")
5
Share
ReportSave
level 2
Original Poster6 years ago
Also, what are you trying to do? It looks favor you are trying to obtain the last insert ID.

Yes, I am trying to gain the last insert ID. What would be the much better method to carry out that?

Thanks.


1
Share
ReportSave
Continue this thread 


level 1
6 years ago · edited 6 years ago
You deserve to attempt returning the identity as component of the insert.

Change your insert from ExecuteNonQuery to ExecuteScalar and also get the identity worths right amethod.

string qryString =
"INSERT INTO YourTable(Col1,Col2,Col3)OUTPUT INSERTED.IdVALUES
val1 ,
val2 ,
val3"utilizing (SqlConnection dbConnection = new SqlConnection(dbConnectString)) using (SqlCommand sqlCmd = new SqlCommand(qryString, dbConnection)) dbConnection.Open(); sqlCmd.Parameters.AddWithValue("
val1", val1); sqlCmd.Parameters.AddWithValue("
val2", val2); sqlCmd.Parameters.AddWithValue("
val3", val3); int newId = (Int32)sqlCmd.ExecuteScalar(); // then execute something via this value. If you don't want to execute this, then follow the suggestion to obtain scope_identity for the session. You'll must reusage the link to obtain it though, which implies it should instantly follow your insert. It can be inline as presented listed below, or in another query that you execute before the insert query's link is closed or falls out of scope and also before you use that connection for anypoint else.

See more: Virtualbox Running In Software Rendering Mode On Virtualbox, Cinnamon 19

INSERT INTO YourTable(
Col1,
Col2,
Col3) VALUES (
Val1,
Val2,
Val3) SELECT SCOPE_IDENTITY
2
Share
ReportSave
level 2
6 years ago
You are correct, and this is just how it would work-related on a production mechanism. I retained it sepaprice for simplicity.


2
Share
ReportSave
level 1
6 years ago

the MAX feature returns a bigint SQL form (Int64 in .net), not an int.


1
Share
ReportSave
level 2
Initial Poster6 years ago

How should I adjust it then?


1
Share
ReportSave
Continue this thread 


level 1
6 years ago
It might aid if you gain out of the habbit of using generic

var And

objectFor every single declaration

It'll be a lot more noticeable where you're going wrong if everything is strongly typed.


1
Share
ReportSave
level 2
6 years ago

Changing all the incidents of var to explicit forms basically cannot make any difference. It would be about as effective as burning incense or making a wish.

ExecuteScalar returns Object:

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar%28v=vs.110%29.aspx

The problem below is that the API being referred to as cannot administer static type indevelopment. The caller has to understand how the provider maps the result of a SQL command also to C# data species, to perform the appropriate cast.

The single area wbelow OP uses declares a variable of type object, they are storing the outcome of a speak to to an API that retransforms just that.

And in the exceptionally line where they hit the problem, they declared the variable expliticly as int, and also it didn't aid.

See more: What"S The Diff Of Spanned And Simple Volume Vs Spanned Volume Object


1
Share
ReportSave
Continue this thread 


level 2
6 years ago
I agree. I use var sparingly.


1
Share
ReportSave
View Entire Discussion (18 Comments)
More write-ups from the csharp community
Continue looking in r/csharp


*

r/csharp
Welcome to csharp
169k
C# devs


615

null referral exceptions


Created Mar 10, 2008
Join
*
*
*
*

*

Top articles march 3first 2015Top write-ups of march, 2015Top short articles 2015
helpclassiccomputers.info Appclassiccomputers.info coinsclassiccomputers.info premiumclassiccomputers.info gifts
aboutcareerspressadvertiseblogTermsContent policyPrivacy policyMod policy
Back to Top