Conversion is not valid

1
 public int ObterTotalAcessos()
    {
        int obtertotal = 0;

        using (var connection = ServiceLocator.ObterConexao())
        {
            var command = connection.CreateCommand();
            command.CommandText = "SELECT SUM (ACESSOS) FROM USUARIO";
            command.Parameters.AddWithValue("total", obtertotal);

            var reader = command.ExecuteReader();
            if (reader.Read())
            {
                // o erro está aqui v

                  obtertotal = reader.GetInt32(0);
            }

        }

        return obtertotal;
    }
  

So guys, my problem is occurring inside the (if). Displays error: Specified cast invalidates. Does anyone have a clue what it can be?

    
asked by anonymous 13.10.2014 / 16:19

1 answer

4

Based on the information you posted, I see two possible situations that are causing this problem:

1) The value returned by your query is null ( DbNull ). To avoid this case, it's worth it:

if (reader.Read())
{
    if (reader[0] == DBNull.Value)
    {
        obtertotal = 0;
    }
    else
    {
        obtertotal = reader.GetInt32(0);
    }
}

2) The value returned by your query is not integer. This can happen because Oracle performs implicit type conversions in aggregate values, arithmetic operations, and so on. To avoid setbacks in this case, I suggest:

(...)
obtertotal = Convert.ToInt32(reader[0]);
(...)
    
13.10.2014 / 16:54