我有包含食谱的表格和包含食谱类别的表格。另一个表中有不同的类别类型。我有类别的可选参数,我的表和 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 然后选择返回 all recipes 但乘以 RECIPE CATEGORIES 表中的categoryTypeId . 因此,如果一个食谱指定了多个类别类型,则我的选择是错误的。
那么我怎样才能使有条件的加入或其他东西,所以当我不想按 recipeCategory 搜索时,不会有任何重复项(重复的标题或 recipeId)
场景是我可以通过 nutritionStyleId OR courseId OR nothing(返回所有食谱)进行搜索
最佳答案
抱歉关于方法语法(它更适合我:))。但这是代码
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 });
关于c# - LINQ Select with join 和 optional where,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16691944/