使用可变参数过滤通用 select
Filtering generic select with changeable parameters
我会保持简单。我有一个接收 0 到 3 个参数的 API 端点。 get 方法如下所示:
[HttpGet("filtrar")]
public ActionResult<List<TipoDocumento>> GetAllPorFiltro(string sigla, int? status, string descricao)
{
return _tipoDocumentoRepositorio.GetAllByFilter(????);
}
_tipoDocumentoRepositorio是一个有DI的接口,实现它的class中的GetAllByFilter()方法是这样的:
public List<T> GetAllByFilter(Expression<Func<T, bool>> filter)
{
return _someContexto.Set<T>()
.Where(filter)
.ToList();
}
事实是:即使我在 ????? (比如
f => f.Sigla.Equals(sigla)
),它让我返回一个空列表。我究竟做错了什么?或者我还应该怎么做才能让它发挥作用?
Obs:我不能把所有的代码都放在这里,因为它不是我的,但我可以争论。可以肯定的是:我正在使用 EF(以及迁移和排序,我是 C# 的新手)。也欢迎任何指向可能回答我的问题的其他 SO 问题的链接。提前致谢。
将您的 GetAllByFilter
更改为 GetAll()
,将 return 更改为 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();
...
}
我会保持简单。我有一个接收 0 到 3 个参数的 API 端点。 get 方法如下所示:
[HttpGet("filtrar")]
public ActionResult<List<TipoDocumento>> GetAllPorFiltro(string sigla, int? status, string descricao)
{
return _tipoDocumentoRepositorio.GetAllByFilter(????);
}
_tipoDocumentoRepositorio是一个有DI的接口,实现它的class中的GetAllByFilter()方法是这样的:
public List<T> GetAllByFilter(Expression<Func<T, bool>> filter)
{
return _someContexto.Set<T>()
.Where(filter)
.ToList();
}
事实是:即使我在 ????? (比如
f => f.Sigla.Equals(sigla)
),它让我返回一个空列表。我究竟做错了什么?或者我还应该怎么做才能让它发挥作用?
Obs:我不能把所有的代码都放在这里,因为它不是我的,但我可以争论。可以肯定的是:我正在使用 EF(以及迁移和排序,我是 C# 的新手)。也欢迎任何指向可能回答我的问题的其他 SO 问题的链接。提前致谢。
将您的 GetAllByFilter
更改为 GetAll()
,将 return 更改为 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();
...
}