【问题标题】:LINQ Select with join and optional whereLINQ Select with join 和可选 where
【发布时间】:2013-05-22 21:27:22
【问题描述】:

我有带有食谱的表格和带有食谱类别的表格。另一个表中有不同的类别类型。我有 optional 类别参数,我的表格和 linq 选择看起来像:

表格:

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's 的数量. 所以如果一个菜谱有更多的 categoryType 指定,我的选择是错误的。

那么我怎样才能使 conditional 加入什么的,所以当我不想按 recipeCategory 搜索时,不会有任何重复(重复的标题或 recipeId)

场景是我可以通过 NutritionStyleId 搜索 OR courseId OR nothing(return all recipes)

【问题讨论】:

    标签: c# .net linq entity-framework


    【解决方案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 });
    

    【讨论】:

    • 如果你使用这种方法语法没问题,但现在我不知道如何为某些表进行 JOIN,例如 RecipeAdditionalInformation 和 RecipesTranslations 和用户......查询语法的加入就像join t in context.recipesTranslations on r.recipeId 等于 t.recipeId 和 recipeAdditional 信息相同,对于用户,连接是通过 userId ... 因为在选择中我需要从 RecipeTranslations(title) 中选择一些数据,从 RecipeAdditionalInformation(rating , imagePath) 和来自用户 (screenName) 所以如果我可以用方法语法写出来,也许解决方案会起作用
    • 您可以像我一样加入所有其他表 - 使用子查询。我对我的回答做了一点修改。
    • maxlego 感谢您的帮助,我已设法将所有内容更改为方法语法并进行测试。 Everythink 工作得很好......我学到了一些新东西......再次感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多