Error converting object type to int

0

I'm doing a select in the database, using ExecScalar returning an object but I can not make a cast of this returned value to integer.

public static int ConsultaPDVsAtivos()
{
    NpgsqlCommand sql = new NpgsqlCommand();
    sql.CommandText = "SELECT COUNT(ID) " +
                      "FROM PDV " +
                      "WHERE ATIVO = TRUE;";

    int pdv_count = (int)ConnectionPostgres.ExecScalar(sql); //ERRO
    return pdv_count;
}

Method that checks the database:

//Executa comando com retorno no banco de dados. param: FbCommand
public static object ExecScalar(NpgsqlCommand SqlCommand)
{
    NpgsqlConnection Conn = null;
    try
    {
        // Abre banco de dados 
        Conn = AbreBD();
        SqlCommand.Connection = Conn;
        return SqlCommand.ExecuteScalar();

    }
    catch (Exception erro)
    {
        MessageBox.Show(String.Format("Erro ao tentar Criar o Objeto Command: \n ERRO: {0}\n FAVOR ENTRAR EM CONTATO COM NOSSO SUPORTE!", erro.Message));
        Conn.Close();
        return false;
    }
    finally
    {
        Conn.Close();
    }
}
    
asked by anonymous 09.02.2017 / 13:03

1 answer

1

According to comments, the return of ConnectionPostgres.ExecScalar(sql) is long wrapped in object .

As long accepts numbers much larger than int , explicit cast is impracticable. So, you can try to convert to int , like this:

 int pdv_count = Convert.ToInt32(ConnectionPostgres.ExecScalar(sql));

Be careful with this because if the return is greater than the maximum value of a int ( int.MaxValue - 2147483647) the conversion will fail.

    
09.02.2017 / 13:30