我想在过滤属性具有值(非空)时使用where条件构建查询。如果使用多个过滤器,则它们必须是AND组合。
当where属性值不为null时,如何组合/添加每个谓词以使最终查询准备好进行过滤?
IQueryable<Customer> filter = null;
Expression<Func<Customer, bool>> predicatetest1 = res => res.test1 == request.test1;
Expression<Func<Customer, bool>> predicatetest2 = res => res.test2 == request.test2;
Expression<Func<Customer, bool>> predicatetest3 = res => res.test3 == request.test3;
if (request.test1 != null)
{
// add the above predicate to the filter
}
if (request.test2 != null)
{
// add the above predicate to the filter
}
if (request.test3 != null)
{
// add the above predicate to the filter
}
答案 0 :(得分:0)
IQueryable<Customer> filter = Context.Customers;
if (request.test1 != null)
{
filter = filter.Where(predicatetest1);
}
if (request.test2 != null)
{
filter = filter.Where(predicatetest2);
}
if (request.test3 != null)
{
filter = filter.Where(predicatetest3);
}
var customers = filter.ToList();
当所有3个属性都不为空时
,以下内容将是等效的Context.Customers.Where(predicatetest1).Where(predicatetest2).Where(predicatetest3).ToList();