简体   繁体   中英

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:

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.

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)

Scenario is that I can search by nutritionStyleId OR courseId OR nothing(return all recipes)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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