这让我疯了。我在这里想念的是什么我正在使用EF,如果我有以下代码:
using (LexiconEntities ctx = new LexiconEntities())
{
var query = from w in ctx.Words
select new WordEntryDataModel
{
Word = w.Anagram,
NumOfAnagrams = w.NumAnagrams.Value,
Length = w.Length.Value,
...
};
SearchCriterion c1 = new SearchCriterion();
SearchCriterion c2 = new SearchCriterion();
c1.MinValue = 3;
c1.MaxValue = 3;
c2.MinValue = 4;
c2.MaxValue = 4;
query = query.Where(w => w.Length >= c1.MinValue && w.Length <= c1.MaxValue);
query = query.Where(w => w.NumOfAnagrams >= c2.MinValue && w.NumOfAnagrams <= c2.MaxValue);
...
}
当我调试查询时,我得到了正确的结果(8条记录)。这也像Linqpad(frickin' rocks)中预期的那样有效。
但是,如果我将搜索条件构造为标准对象列表,并通过迭代搜索条件动态添加Where()子句,如下所示:
foreach (SearchCriterion c in criteria.SearchCriteria)
{
switch (c.Type)
{
case SearchCriterionType.WordLength:
query = query.Where(w => w.Length >= c.MinValue && w.Length <= c.MaxValue);
break;
case SearchCriterionType.NumberOfAnagrams:
query = query.Where(w => w.NumOfAnagrams >= c.MinValue && w.NumOfAnagrams <= c.MaxValue);
break;
...
case SearchCriterionType.NumberOfVowels:
query = query.Where(w => w.NumOfVowels >= c.MinValue && w.NumOfVowels <= c.MaxValue);
break;
}
}
...
我得到完全不同(和不正确)的结果。我调试了switch语句,我的搜索条件有两个正确构造的标准对象设置为正确的值。有条件地添加了我的查询不喜欢的where子句。
我做错了什么?