[英]LINQ Select with join and optional where
我有帶食譜的桌子和帶食譜類別的桌子。 另一個表中有不同的類別類型 。 我有類別的可選參數,我的表和linq select看起來像:
表:
RECIPE
recipeId title
RECIPE CATEGORIES
recipeCategoryId recipeId categoryId categoryTypeId
var result = from r in context.Recipes
join c in context.RecipeCategories on r.recipeId equals c.recipeId
where (nutritionStyleId == 0 || c.categoryId == nutritionStyleId )
&& (courseId == 0 || c.categoryId == courseId)
select new
{
r.recipeId,
r.title
};
您只能按一種類型進行選擇 ( 按CourseId或NutritionStyleId或無選擇 (如果NutritionStyleId和courseId == 0)。問題是當NutritionStyleId和courseId為0時,選擇返回所有 配方,但乘以數量RECIPE CATEGORIES表中的categoryTypeId ,因此,如果一個配方指定了更多categoryType,則我的選擇是錯誤的。
所以我該如何進行條件連接或其他什么操作,所以當我不想按recipeCategory進行搜索時,將不會有任何重復(標題或菜譜ID重復)
情景是,我可以通過nutritionStyleId 或 courseId 或沒有(返回所有配方)搜索
很抱歉方法語法(它更適合我:))。 但是這是代碼
context.Recipes
.Where(x => x.RecipeCategories.Any(rc => (nutritionStyleId == 0 || rc.categoryId == nutritionStyleId) && (courseId == 0 || rc.categoryId == courseId))
.Select(x => new { x.recipeId, x.title });
編輯:加入翻譯:
context.Recipes
.Where(x => x.RecipeCategories.Any(rc => (nutritionStyleId == 0 || rc.categoryId == nutritionStyleId) && (courseId == 0 || rc.categoryId == courseId))
.Select(x => new { x.recipeId, Title = x.Translations.FirstOrDefault(t => t.Language == language).Title });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.