我正在尝试将一个bigint从SQL Server转换为它在c#中的等价物,但是Visual Studio一直强迫我尝试将它转换为int,这会引发"指定的转换无效"错误.我试图将它转换为long,Int64,int等.这样做的正确方法是什么?我的代码看起来像这样:
var id = 0;
//Omitted code
if (reader.Read())
{
id = (int) reader["id"];
}
//More code
Run Code Online (Sandbox Code Playgroud)
如图following table
所示,SQL Server bigint
映射到.NET的Int64
结构:
long id = 0;
//Omitted code
if (reader.Read())
{
id = (long) reader["id"];
}
Run Code Online (Sandbox Code Playgroud)
如果这是抛出一个InvalidCastException
你完全没有bigint
在你的dtaabase中,你可能想要检查调试器中的实际类型使用reader["id"].GetType()
.
顺便说通知我你如何更换var id = 0;
与long id = 0;
这实际上是声明类型的变量Int64
来代替Int32
.如果您想使用C#变量推断,请确保以正确的方式执行此操作:var id = 0L;
顺便说一句,如果你不想投,你可以试试这个替代方案:
long id = 0;
//Omitted code
if (reader.Read())
{
id = reader.GetInt64(reader.GetOrdinal("id"));
}
Run Code Online (Sandbox Code Playgroud)