Ado.Net和BigInteger导致Int64的无效强制转换异常

时间:2014-06-11 14:43:21

标签: c# .net .net-4.0 ado.net biginteger

我有一个简单的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

有什么问题?

2 个答案:

答案 0 :(得分:3)

BigIntBigInteger不符。它对应long / Int64。您可能应该从商家代码中删除所有BigInteger用法并使用long。 ADO.NET不理解BigInteger

答案 1 :(得分:1)

您的BigInteger是System.Numerics中的复杂类型,它不会映射到SQL BigInt。作为一般规则,通常在将C#类型映射到SQL DB类型时,其基本类型(如long,int,int64,string ...)在这种情况下,您的辅助错误消息建议使用Int64。如果您决定将BigInteger作为传入的参数,那么您应该将其转换为Method内部的长整数。您还可以在SqlParameter的实例化中指定SQL Type。

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 };

        //BigInteger to Int64 conversion long and Int64 is the same type
        long execId = (long) executionId;

        var parameterExecutionId = new SqlParameter("@execution_id", SqlDbType.BigInt, execId);
        command.Parameters.Add(parameterExecutionId);
        using (var reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                status = Convert.ToInt32(reader["status"]);
            }
        }
        connection.Close();
    }
    return status;    
}