我真的很喜歡PredicateBuilder。它允許我非常動態地構建各種查詢。謂詞變量可以傳遞給不同的對象,並且可以使用他們知道的值添加它,等等。除非我需要在散列集合上使用.Contains。 Bzzt!崩潰和燒傷。LINQ Predicates中使用的收藏範圍
例如(例如/僞代碼,這可能會或可能不會編譯/運行):
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異常:方法「布爾包含(Int32)已」由於所選ID的HashSet不在範圍內,因此沒有支持轉換到SQL。如果我用同樣的方法完成這一切,那麼它工作正常。
我需要知道正確的方法來讓我的謂詞在那裏解決或編譯或者其他任何東西,以便它可以在聲明HashSet的不同範圍內使用。任何幫助?
更新:我有這個錯誤。下面的代碼工作正常,所以沒有範圍衝突。謝謝Jay。
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()));
好的,我會工作我的代碼了一下,看看我是否在這裏走錯了路。謝謝。 – sliderhouserules 2010-08-05 04:49:49