2009-11-29 23 views
1

我有一個配方表,其中有一個基於多個基礎的相關配料表 。使用Linq在很多桌子上選擇

如何選擇使用Linq成分 ,該成分具有一個成分名稱列,並且它應包含指定詞的 。

這就是我試過的。

IQueryable<OurRecipes.Domain.Linq2Sql.Recipe> recipes = _dbctx.Recipes.AsQueryable(); 

    foreach (string word in searchdata.Keywords) 
    { 
     recipes = recipes.Where(r => r.RecipeTitle.Contains(word)); 
     recipes = recipes.Where(r => r.Ingredients.Where(i => i.IngredientName.Contains(word))); 
    } 

我得到不能轉換類型'等'到布爾錯誤。

任何想法 馬爾科姆

回答

2

錯誤就出在這裏:

recipes = recipes.Where(r => r.Ingredients.Where(i => i.IngredientName.Contains(word))); 

Where條件必須返回一個布爾值,在這種情況下,r.Ingredients.Where(i => i.IngredientName.Contains(word))不會返回一個布爾值,因此錯誤。

這是你如何解決這個問題:

recipes = recipes.Where(i => i.Ingredients.Any(row=>row.IngredientName.Contains(word))); 
+0

+1,解決方法是將該行更改爲'recipes = recipes.Where(r => r.Ingredients.Count(i => i.IngredientName.Contains(word))> 0);' – 2009-11-29 12:57:53

+0

你的解決方案不會編譯,因爲'我'是'Recipie'。它沒有'IngredientName'。 – 2009-11-29 12:58:11

+0

答覆更新... – Graviton 2009-11-29 13:39:12

1
r.Ingredients.Where(i => i.IngredientName.Contains(word)));  

r.Ingredients.Any(i => i.IngredientName.Contains(word)));  

順便說一句取代,我喜歡像SQL語法的更多,因爲它更netural。相同:

from r in _dbctx.Recipes 
where r.Ingredients.Any(i => i.IngredientName.Contains(word))); 
select r; 

這將選擇具有名稱包含單詞的成分的所有收益。