从 SQLDataReader 读取结果时无效的强制转换异常

问题描述:

我的存储过程:

    @UserName nvarchar(64),

    AS

    BEGIN
    SELECT MPU.UserName, SUM(TS.Monday)as Monday //TS.Monday contains float value
    FROM dbo.MapTask MT JOIN dbo.MapPU MPU
    ON MPU.ID = MT.MPUID
    JOIN dbo.TimeSheet TS
    ON MT.TMSID = TS.ID
    WHERE MT.StartDate = @StartDate_int and MPU.UserName = @UserName
    GROUP BY MPU.UserName
    END

在我的 C# 代码中

SqlDataReader reader = command.ExecuteReader();

        while (reader.Read())
        {
            float monday = (float)reader["Monday"]; // Invalid cast exception
        }

谁能告诉我我做错了什么?谢谢.

Can somebody tell me what I did wrong ? Thank you.

我的猜测是返回的值是一个装箱的 double 而不是 float.当您拆箱时,类型必须完全正确.所以假设我是对的并且它不是 decimal 或类似的东西,你可以使用:

My guess is that the value is being returned as a boxed double instead of float. When you unbox the type has to be exactly right. So assuming I'm right and it's not decimal or something like that, you could use:

float monday = (float) (double) reader["Monday"];

它会起作用.不过还是挺丑的.如果您使用 SqlDataReader.GetFloat代码>它应该是正确的如果它确实是一个单精度值,并且更清楚(IMO)发生了什么.

and it would work. That's pretty ugly though. If you use SqlDataReader.GetFloat it should get it right if it's genuinely a single-precision value, and it's clearer (IMO) what's going on.

另一方面,您的数据可能实际上作为double从数据库返回,在这种情况下,您应该(IMO)使用:

On the other hand, your data could actually be coming back from the database as a double, in which case you should (IMO) use:

float monday = (float) reader.GetDouble(column);

顺便说一句,首先您确定 float 实际上是最合适的类型吗?通常decimal 更合适...

As an aside, are you sure that float is actually the most appropriate type here in the first place? Often decimal is more appropriate...