我试图将2个查询过滤器与mongodb驱动程序结合使用,但是框架仅返回“ System.InvalidOperationException:'x.MyBool2不支持。'“
以下所有表达式均成功,但最后一个表达式除外,我试图在其中执行组合查询。
我在做什么错了?
public async Task GetTest()
{
Expression<Func<PostDto, bool>> filter = x => x.MyBool1 == true;
Expression<Func<PostDto, bool>> filter1 = x => x.MyBool2 == true;
Expression<Func<PostDto, bool>> filter2 = x => x.MyBool1 && x.MyBool2;
var andAlsoExpression = Expression.AndAlso(filter.Body, filter1.Body);
var combinedFilter = Expression.Lambda<Func<PostDto, bool>>(andAlsoExpression, filter.Parameters);
var result = await Collection.AsQueryable().Where(filter).ToListAsync();
var result1 = await Collection.AsQueryable().Where(filter1).ToListAsync();
var result2 = await Collection.AsQueryable().Where(filter2).ToListAsync();
var result3 = await Collection.AsQueryable().Where(x => x.MyBool1 && x.MyBool2).ToListAsync();
var result4 = await Collection.AsQueryable().Where(combinedFilter).ToListAsync();
Debugger.Break();
}
答案 0 :(得分:0)
Marc Gravell的AndAlso扩展对我有帮助:
static Expression<Func<T, bool>> AndAlso<T>(
this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
// need to detect whether they use the same
// parameter instance; if not, they need fixing
ParameterExpression param = expr1.Parameters[0];
if (ReferenceEquals(param, expr2.Parameters[0]))
{
// simple version
return Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(expr1.Body, expr2.Body), param);
}
// otherwise, keep expr1 "as is" and invoke expr2
return Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(
expr1.Body,
Expression.Invoke(expr2, param)), param);
}
来源:Combining two expressions (Expression<Func<T, bool>>)
使用此扩展名,而不是我的AndAlso&Expression.Lambda部分解决了问题。