Conversion is not valid

Asked

Viewed 4,703 times

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 (if). Displays error: Specified conversion invalidates. Someone knows what they pose to be?

  • What is the error message?

  • Specified conversion is not valid. Error happens inside in IF

  • 1

    I see that you are not a new user, so please read this page: [Ask] to improve the quality of your questions!

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 is worth consisting:

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 into aggregated values, arithmetic operations, etc. To avoid setbacks in this case, I suggest:

(...)
obtertotal = Convert.ToInt32(reader[0]);
(...)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.