我真的很喜欢PredicateBuilder。它允许我非常动态地构建各种查询。谓词变量可以传递给不同的对象,并且他们可以添加他们知道的值等。除非我需要在散列集合上使用 .Contains 。呸!崩溃和燃烧。
例如(示例/伪代码,这可能会或可能不会编译/运行):
protected Expression<Func<MyClass, bool>> GetWherePredicate()
{
string[] selectedValues = Request.Form.GetValues("checkbox1") ?? new string[0];
HashSet<int> selectedIDs = new HashSet<int>(selectedValues.Cast<int>());
Expression<Func<MyClass, bool>> predicate = PredicateBuilder.True<MyClass>();
predicate = predicate.And(s => selectedIDs.Contains(s.ID));
return predicate;
}
protected void Retrieve()
{
Expression<Func<MyClass, bool>> predicate = GetWherePredicate();
IEnumerable<MyClass> retrievedValues = MyDataContext.GetTable<MyClass>.Where(predicate);
}
当我尝试这样做时,我得到一个NotSupportedException: Method 'Boolean Contains(Int32)' has no supported translation to SQL due to selectedIDs HashSet不在范围内。如果我用同样的方法做这一切,那么它工作得很好。
我需要知道正确的方法来让我的谓词在那里解析或编译或其他任何东西,以便它可以在与声明 HashSet 的地方不同的范围内使用。有什么帮助吗?
更新:我错了。下面的代码工作正常,所以没有范围冲突。谢谢杰。
string[] selectedValues = Request.Form.GetValues("checkbox1") ?? new string[0];
Expression<Func<MyClass, bool>> predicate = PredicateBuilder.True<MyClass>();
predicate = predicate.And(s => selectedValues.Contains(s.ID.ToString()));