How to check if the query did not return data?

Asked

Viewed 1,873 times

1

I have a query and would like to know if the same returned data.

//classe aplicação-
private List<tb_cabecalho> TransformaReaderEmListaObjetos(SqlDataReader reader)
{
    var retornando = new List<tb_cabecalho>();
    while (reader.Read())
    {

        tb_cabecalho tabela = new tb_cabecalho()
        {
            campofixo = "H",
            cnpjdoecomerce = "61549259000180",
            dataincial = reader["DataInicial"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(reader["DataInicial"]),
            datafinal = reader["DataFinal"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(reader["DataFinal"])
        };

        retornando.Add(tabela);
    }
    reader.Close();
    return retornando;
}

    /// <summary>
    /// Aqui estou retornando os dados do cabecalho
    /// </summary>
    var tbuscar = new cabecalhoAplicacao();
    var retorno = tbuscar.DadosDoCabecalho();
  • Do you want to test inside the Transform methodsby testing objects or want to test the return of it?

  • I want to check if the Transformeaderemlistaobjects is returning the data because if vim empty will generate an error

  • The GOKU Ssjgod answer.

2 answers

2


If you want to check if your method is returning value, the simplest to do in this case is to use the one if lista == null is a Count() > 0.

List<tb_cabecalho> lista = TransformaReaderEmListaObjetos(reader);
if(lista != null && lista.Count > 0)
{
   // Todo... 
}

Or just use the Any()

if(lista.Any())
{
   // Todo... 
}
  • Please if lista really is a List, use the property Count instead of the method Count().

  • I hope it’s really a list

  • Just as a hint, you can use lista?.Any() instead of checking if the object is null and the property Count

  • It’s also a good tip

  • 1

    I appreciate all your help

0

You can check if your query returned any line:

if(!reader.HasRow) return null;

On the other side, where you consume the method, just check if the return is different from null. You must make this check before the while

  • Friend, you checked this: var returning = new List<tb_cabecalho>();

  • could improve the response

  • var returning = new List<tb_cabecalho>(); this just creates a list of objects 'tb_cabecalho' Now to know if the query Sqldatareader has result, just use the cited code. But you can check if the list has items. if(returned.Count > 0) Return null;

Browser other questions tagged

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