I know the usual answers for this and they don't seem to apply.
We have a process that goes through data from numerous vendors and gets it into one consistent stream. We added a vendor recently that required a change to our primary key to a bigint.
Some of the string massaging was just easier to do in C#, so I changed the C# code from
primaryKey = reader.GetInt32(0);
to
primaryKey = reader.GetInt64(0);
figuring that the older vendors in the system would just cast cleanly up to Int64.
I got everybody up and running and I noticed that some but not all of one of the older vendor's records (the int32 primary key) were getting processed. Looking in the log files, I was seeing InvalidCastException on the reader.GetInt64() call processing some batches.
I know the usual response is "Oh, you're probably getting nulls", but
- it is a primary key. It can't be null
- The code's been running with the reader.GetInt32(0) call for over a decade
- all the numbers in all the batches (successful and unsuccessful) are in the 181 million range
I changed the code to throw an ArgumentNullException if IsDBNull() came back true, but that never tripped.
The stack trace has
at System.Data.SqlClient.SqlBuffer.get_Int64()
but without source or line number it's hard to get farther.
I put
CAST(keyID as bigint) keyID
in the stored procedure returning the batches, and the issue has gone away.
Still curious though. Why would reader.GetInt64() throw an InvalidCastException sporadically when given an Int32 in the query result?
reader.GetFieldType