Skip to main content
 首页 » 编程设计

c#之Ado.Net 和 BigInteger 导致对 Int64 的无效转换异常

2024年02月06日16jyk

我有一个简单的 SQL 查询要在 Ado.Net 中执行。它有一个参数,一个 BigInteger。

public int MyMethod(BigInteger executionId) 
{ 
    int status = -1; 
    using (var connection = new SqlConnection(this.ConnectionString)) 
    { 
        connection.Open(); 
        var command = new SqlCommand("select ... where execution_id=@execution_id", connection) { CommandType = CommandType.Text }; 
        var parameterExecutionId = new SqlParameter("@execution_id", executionId) { SqlDbType = SqlDbType.BigInt }; 
        command.Parameters.Add(parameterExecutionId); 
        using (var reader = command.ExecuteReader()) 
        { 
            while (reader.Read()) 
            { 
                status = Convert.ToInt32(reader["status"]); 
            } 
        } 
        connection.Close(); 
    } 
    return status;     
} 

当我运行此代码时,ExecuteReader 出现此异常:

An exception of type 'System.InvalidCastException'  
occurred in System.Data.dll but was not handled in user code 
 
Additional information: Failed to convert parameter  
value from a BigInteger to a Int64. 

数据库确实将 execution_id 列设置为 bigint。

怎么了?

请您参考如下方法:

BigInt 不对应于 BigInteger。对应于long/Int64。您可能应该从您的业务代码中删除所有 BigInteger 用法并使用 long。 ADO.NET 不理解 BigInteger。