我试图将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();
}
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部分解决了这个问题。