【发布时间】:2021-09-01 10:29:16
【问题描述】:
我有主要的 EF 核心查询,它通过 IQueryable.Where() 向它附加一些 AND 搜索条件。没问题。
并通过Expression<Func<T, bool>> orFilter 对其应用一些 OR 搜索条件。
它与 Or via 连接:orFilter = orFilter.Or(p=>p.Prop == foo);
最后,它将通过 mainQuery.Where(orFilter) 作为 AND 搜索条件应用于主查询;没问题。
但是 OR 搜索条件之一是针对另一个表,需要连接到另一个表,它返回 IQueryableorFilter = orFilter.Or(joinQuery.Expression as Expression<Func<Product, bool>>); 将它应用到 orFilter 但它不起作用。
或者有什么等效的实现方式吗?
IQueryable<Product> records = DBContext.Product
.Include(p => p.Item1)
...;
if (filterANDCriteria1.HasValue)
{
records= records.Where(p.xxx == filterANDCriteria1);
}
Expression<Func<Product, bool>> orFilter= null;
if(filterOrCriteriaP1.HasValue)
{
orFilter= orFilter.Or(p=>p.yyy==filterOrCriteriaP1 );
}
if(filterOrCriteriaP2.HasValue)
{
//join another table e.g. Category pseudo code
IQueryable<Product> joinQuery =
records.Join(Category.EntityId == Product.Id and Category.EntityType == EntityType.Product and Category.FieldFoo == filterOrCriteriaP2),
(product,category)=> product;
//Want to append the query to orFilter here but it not work and return null
orFilter = orFilter.Or(joinQuery.Expression as Expression<Func<Product, bool>>); //return null
//It only works for AND query, following code will return the products that match join result and other filter (like filterANDCriteria1)
// records = joinQuery;
}
if(orFilter!=null)
{
//Apply whole orFilter as AND filter to main query
records = records.Where(orFilter);
}
return records.ToList();
【问题讨论】:
-
实际上我认为我通过 Concat 表达式
> 制作了一个 PredicateBuilder。但我也想将 IQueryable 附加到 PredicateBuilder。喜欢 var predicate = PredicateBuilder.False<Foo>(); predicate.Or(convert an IQueryable here to predicate) -
我不要
t understand how do you plan to convertIQueryable`做谓词?
标签: c# entity-framework entity-framework-core