質問

I get an Invalid Cast Exception on the following line:

DestMinSeq = (long)rdr["MinSeq"];

When I change the query to cast MinSeq to BIGINT instead of INT, it works.

Question: why should it be illegal to cast a short to a long?

Environment:

VS 2012 SSIS project script task. 
ADO.NET connection manager. 
SQL Server 2012.
役に立ちましたか?

解決

Question: why should it be illegal to cast a short to a long?

You're trying to cast a boxed short to a long. You can see this without a database:

int x = 10;
object o = x;
long y = (long) o; // Bang!

If you cast to the right type when unboxing, then cast to the type you really want, it's fine:

DestMinSeq = (long)(int)rdr["MinSeq]";

(I suspect you want int rather than short, but you'll have to check.)

他のヒント

The problem is that rdr["MinSeq"] is of type object (actually a int boxed as an object). When you try to cast the object as a long it then gives you an invalid cast because the compiler cannot simply cast an object of type object to something other than the actual boxed type (in this case int).

You can try this instead,

 DestMinSeq = Convert.ToInt64(rdr["MinSeq"]);

Or what @Jon Skeet suggested, which actually looks fancier,

 DestMinSeq = (long)(int)rdr["MinSeq"];
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top