Search code examples
c#sqlsql-servert-sqlstored-procedures

Invalid cast exception when reading result from SQLDataReader


My stored procedure:

@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

In my C# code

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.


Solution

  • 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"];
    

    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.

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

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