Search Filter

2

I have an entity of Items that relates to the table of products and it is already in production and is working perfectly! Now I need to create a search report where the user can determine through the filters the conditions of this query. The query fields that the user can choose are:

  • Date From - Date Request From To
  • Store
  • Item
  • Brand
  • Payment form.

The report is very simple and the result will be displayed through a View with List. The report has already been created without using the fields previously reported. I'm using EntityFramework in queries and for this report I'm currently using this query:

return Db.TabCadStatusOrdemServicoItem.ToList().OrderByDescending(x => x.Descricao);

The question is: how do I include the fields in the above query knowing that for some fields the user can select the option all (eg store)?

Thanks for the strength!

    
asked by anonymous 25.05.2016 / 16:05

2 answers

1

I think this answer here may be useful for you .

In your case, you can do a ViewModel whose fields are Nullable :

public class ParametrosPesquisaViewModel
{
    public DateTime? DataInicial { get; set; }
    public DateTime? DataFinal { get; set; }
    public int? LojaId { get; set; }
    public int? ItemId { get; set; }
    public int? MarcaId { get; set; }

    public IEnumerable<TabCadStatusOrdemServicoItem> Resultados { get; set; }
}

Predicate construction example:

        var query = db.TabCadStatusOrdemServicoItem.AsQueryable();
        if (viewModel.DataInicial != null)
        {
            if (viewModel.DataFinal != null)
            {
                query = query.Where(a => a.Data >= viewModel.DataInicial && a.Data <= viewModel.DataFinal);
            }
            else
            {
                query = query.Where(a => DbFunctions.TruncateTime(a.Data) == viewModel.DataInicial);
            }
        }

        if (viewModel.LojaId != null)
        {
            query = query.Where(a => a.LojaId == (int)viewModel.LojaId);
        }

        // E assim por diante.

         return query.ToList();
    
25.05.2016 / 19:33
2

If I understood the question correctly, you could do something like this:

var result = Db.TabCadStatusOrdemServicoItem.ToList();

//Para cada campo do filtro, adicionar um bloco If igual ao abaixo
if (!modelFiltro.Foo.IsNullOrWhiteSpace())
{
    result = result.Where(x => x.Foo.Equals(modelFiltro.Foo))
}


return result.OrderByDescending(x => x.Descricao);

Of course, if you select "All" in the store filter, you simply do not send any store ID.

    
25.05.2016 / 16:28