使用可变参数过滤通用选择

里卡多·桑帕约

我会保持简单。我有一个API端点,可以接收0到3个参数。get方法如下所示:

[HttpGet("filtrar")]
public ActionResult<List<TipoDocumento>> GetAllPorFiltro(string sigla, int? status, string descricao)
{
    return _tipoDocumentoRepositorio.GetAllByFilter(????);
}

_tipoDocumentoRepositorio是具有DI的接口,实现它的类中的方法GetAllByFilter()如下所示:

public List<T> GetAllByFilter(Expression<Func<T, bool>> filter)
{
    return _someContexto.Set<T>()
        .Where(filter)
        .ToList();
}

事实是:即使我将一个函数放在????上 (喜欢

f => f.Sigla.Equals(sigla)

),这使我始终返回一个空列表。我究竟做错了什么?还是我应该做些什么才能使其起作用?

Obs:我不能将所有代码都放在这里,因为它不是我的,但是我可以争论。可以肯定的是:我正在使用EF(以及Migration and sort,我是C#的新手)。并且与其他可能回答我的问题的SO问题的链接也都受到欢迎。提前致谢。

科里亚金

将您的更改GetAllByFilter为公正GetAll()并返回公正IQueriable<T>

创建扩展方法:

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;
}

像这样使用它:

[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();
     ...
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章