简体   繁体   English

LINQ选择带有连接和可选位置

[英]LINQ Select with join and optional where

I have table with recipes and table with recipe categories . 我有带食谱的桌子和带食谱类别的桌子。 There are diferent type of categories in another table. 另一个表中有不同的类别类型 I have optional parameter for category, my tables and linq select looks like: 我有类别的可选参数,我的表和linq select看起来像:

TABLES: 表:

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
             };

You can only select by one type of category( by courseId or by nutritionStyleId or by none (if nutritionStyleId and courseId == 0). The problem is when nutritionStyleId and courseId is 0 then the select return me all the recipes but multiply by number of categoryTypeId's in RECIPE CATEGORIES table. So if one recipe have more categoryType's specified, my select is wrong. 您只能按一种类型进行选择按CourseId或NutritionStyleId或无选择 (如果NutritionStyleId和courseId == 0)。问题是当NutritionStyleId和courseId为0时,选择返回所有 配方,乘以数量RECIPE CATEGORIES表中的categoryTypeId ,因此,如果一个配方指定了更多categoryType,则我的选择是错误的。

So how can I make conditional join or something, so when I dont want to search by recipeCategory there won`t be any duplicates (duplicated title or recipeId) 所以我该如何进行条件连接或其他什么操作,所以当我不想按recipeCategory进行搜索时,将不会有任何重复(标题或菜谱ID重复)

Scenario is that I can search by nutritionStyleId OR courseId OR nothing(return all recipes) 情景是,我可以通过nutritionStyleId courseId 没有(返回所有配方)搜索

Sorry about method syntax (it suits me better :)). 很抱歉方法语法(它更适合我:))。 But heres the code 但是这是代码

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 });

EDIT: joining translations: 编辑:加入翻译:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM