我正在创建一个查询以从数据库中返回一些数据。我正在传递一个我想要过滤的 id 列表。如果过滤器列表为空或为空,我想返回所有内容。
我有一个扩展方法可以让我这样做
,它query
是一个可以为空的整数的列表(不要问!)如果列表为非空并且其中包含某些内容,则该方法返回 true。IQueryable
Ids
ListHasElements
var filteredList = query.WhereIf(ListHasElements(Ids), s => Ids.Contains(s.Id.Value));
但是,当我构建时,query
我使用我喜欢的查询语法
var query = from a in dbContext.as
join b in dbContext.bs on a.Id.ToString() equals b.Id
join cin dbContext.cs on b.Id equals c.Id into bcJoin
from items in bcJoin.DefaultIfEmpty()
where b.Sent >= fromDate
where b.Sent <= toDate
select new{a=a.thing, b=b.thingy, q=items.q,Id=a.Id}
然后我必须插入第一行来做我的魔法 WhereIf 过滤器。最后进一步选择分组并创建我的输出对象(代码未显示!)
扩展方法如下所示。
public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition,
Expression<Func<TSource, bool>> predicate)
{
return condition ? source.Where(predicate) : source;
}
我可以在查询语法查询中直接使用此方法吗?