C# 使用可变参数筛选泛型选择

C# 使用可变参数筛选泛型选择,c#,generics,entity-framework-core,where-clause,C#,Generics,Entity Framework Core,Where Clause,我会保持简单。我有一个接收0到3个参数的API端点。get方法如下所示: [HttpGet("filtrar")] public ActionResult<List<TipoDocumento>> GetAllPorFiltro(string sigla, int? status, string descricao) { return _tipoDocumentoRepositorio.GetAllByFilter(????); } public List<

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

[HttpGet("filtrar")]
public ActionResult<List<TipoDocumento>> GetAllPorFiltro(string sigla, int? status, string descricao)
{
    return _tipoDocumentoRepositorio.GetAllByFilter(????);
}
public List<T> GetAllByFilter(Expression<Func<T, bool>> filter)
{
    return _someContexto.Set<T>()
        .Where(filter)
        .ToList();
}
),它让我返回一个空列表。我做错了什么?或者我还应该做些什么来让它工作


Obs:我不能把所有的代码都放在这里,因为它不是我的,但我可以争辩。可以肯定的是:我使用的是EF(还有迁移和排序,我是C#新手)。同时,我们也欢迎任何可以回答我问题的其他SO问题的链接。提前感谢。

将您的
GetAllByFilter
更改为just
GetAll()
并返回just
iQuery

创建扩展方法:

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;
}
公共静态IQueryable where if(
这是一个可靠的来源,布尔条件,
表达式(谓词)
{
如果(条件)
返回source.Where(谓词);
其他的
返回源;
}
这样使用:

[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();
     ...
}
[HttpGet(“filtrar”)]
public ActionResult GetAllPorFiltro(字符串符号、int?状态、字符串描述)
{
变量res=_tipodocumentepositorio
.GetAll()
.wheref(!String.IsNullOrEmpty(sigla),q=>q.sigla==sigla)
.WhereIf(status.HasValue,q=>q.sigla==sigla.Value)
.wheref(!String.IsNullOrEmpty(descripcao),q=>q.descripcao==descripcao)
.ToList();
...
}

可以肯定的是,你知道
string.Equals
是区分大小写的,所以
“Hello Worlds”
并不等于
“Hello Worlds”
。我知道,但我两个都试过了,没有一个成功。我不知道我是否需要对迁移或其他事情做一些修改(我会编辑它以确保我在项目中使用EF)…您使用
表达式过滤器而不是仅使用
Func过滤器
?@RandRandom:因为他正在使用EF,EF将表达式转换为SQL。Func从不在C#中执行。我认为,它是否区分大小写取决于数据库和使用的排序规则。SQL Server默认不区分大小写,Oracle默认区分大小写。
[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();
     ...
}