我有食谱的表格和食谱类别的表格。另一个表中有不同的类别。我有类别的可选参数,我的表和linq选择看起来像:
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
};
你只能选择一种类型的类别( by courseId或者NutrStyleId或者没有(如果nutrStyleId和courseId == 0)。问题是当营养风格并且courseId为0然后选择返回全部 食谱,但是乘以在RECIPE CATEGORIES表中 categoryTypeId 的数量因此,如果一个配方指定了更多的categoryType,那么我的选择是错误的。
那么如何才能使条件加入或者其他东西,所以当我不想按recipeCategory搜索时,不会有任何重复(重复的标题或recipeId)
情景是我可以通过营养风格搜索或 courseId 或没有(返回所有食谱)
答案 0 :(得分:1)
抱歉方法语法(它更适合我:))。但继续代码
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 });