Return DataReader to field type bool

4

I need to return a field that is of type bool :

    public List<TB_USUARIO> ListarTodos()
    {
        var strQuery = "select * from tb_usuario";

        using (contexto = new Contexto())
        {
            var retornoDataReader = contexto.ExecutaComandoComRetorno(strQuery);
            return TransformaReaderEmListaObjetos(retornoDataReader);
        }

    }

    private List<TB_USUARIO> TransformaReaderEmListaObjetos(SqlDataReader reader)
    {
        var retornando = new List<TB_USUARIO>();
        while (reader.Read())
        {

            TB_USUARIO tabela = new TB_USUARIO()
            {
                IDUSUARIO = reader["IDUSUARIO"] == DBNull.Value ? 0 : Convert.ToInt32(reader["IDUSUARIO"]),
                NOME = reader["NOME"] == DBNull.Value ? string.Empty : reader["NOME"].ToString(),
                LOGIN = reader["LOGIN"] == DBNull.Value ? string.Empty : reader["LOGIN"].ToString(),
                SENHA = reader["SENHA"] == DBNull.Value ? string.Empty : reader["SENHA"].ToString(),
                ADMINISTRADOR = (bool)reader["ADMINISTRADOR"] //este campo
        };

            retornando.Add(tabela);
        }
        reader.Close();
        return retornando;
    }
    
asked by anonymous 11.05.2016 / 17:36

2 answers

5

Just do this:

 ADMINISTRADOR = reader["ADMINISTRADOR"] as string == "S"; //se tem S ou N

Since the column is not originally a boolean but a text, it should be compared to the text that represents the true state.

Although it's late, I advise you not to use all uppercase names and prefixes in names.

    
11.05.2016 / 18:02
3

According to the comments, the ADMINISTRADOR column is of type char and you save the S / N values.

The only explicit string conversion to boolean you can do is to convert "true" (to true ) or "false" (to false ).

The solution is you validate the value that exists in the column, this way

ADMINISTRADOR = (string)reader["ADMINISTRADOR"] == "S"

If the ADMISTRADOR column does not accept nulls, otherwise use the as operator (in this case whereas null corresponds to false .

ADMINISTRADOR = reader["ADMINISTRADOR"] as string == "S"
    
11.05.2016 / 18:03