I'll keep it simple. I have an API endpoint that receives 0 to 3 parameters. The get method look like this:
[HttpGet("filtrar")]
public ActionResult<List<TipoDocumento>> GetAllPorFiltro(string sigla, int? status, string descricao)
{
return _tipoDocumentoRepositorio.GetAllByFilter(????);
}
The _tipoDocumentoRepositorio is an interface that has DI, and the method GetAllByFilter() in the class that implements it looks like this:
public List<T> GetAllByFilter(Expression<Func<T, bool>> filter)
{
return _someContexto.Set<T>()
.Where(filter)
.ToList();
}
The fact is: even though I put a function on ???? (like
f => f.Sigla.Equals(sigla)
), it keeps me returning an empty List. What am I doing wrong? Or what else should I do to make it work?
Obs: I can't put all of the code here cause it's not mine, but I can argue. To be sure: I'm using EF (and Migration and sort, I'm new in C#). And any links to other SO question that may answer my question is welcomed as well. Thanks in advance.
Change your GetAllByFilter
to just GetAll()
and return just IQueriable<T>
Create an extension method:
public static IQueryable<T> WhereIf<T>(
this IQueryable<T> source, bool condition,
Expression<Func<T, bool>> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}
Use it like that:
[HttpGet("filtrar")]
public ActionResult<List<TipoDocumento>> GetAllPorFiltro(string sigla, int? status, string descricao)
{
var res = _tipoDocumentoRepositorio
.GetAll()
.WhereIf(!String.IsNullOrEmpty(sigla), q => q.sigla == sigla)
.WhereIf(status.HasValue, q => q.sigla == sigla.Value)
.WhereIf(!String.IsNullOrEmpty(descricao), q => q.descricao == descricao)
.ToList();
...
}