【问题标题】:How to write a LINQ query or Lambda expression on one to many relation with filter如何在与过滤器的一对多关系上编写 LINQ 查询或 Lambda 表达式
【发布时间】:2010-03-03 00:38:09
【问题描述】:

我在考虑如何在一对多关系上编写适当的 LINQ 查询或 lambda 表达式,同时在实体框架的“多”端对实体进行适当的过滤。

所以两个实体是:

食谱
身份证
姓名 类型 [小|大]

成分
身份证
配方ID
名称
类型 [常规|异国情调]

那么如何编写一个 LINQ 查询来选择具有异国情调的小配方?

可能是这样的:

var smallExoticRecipes = contex.Recipes.Include("Ingredients").Where(recipe => recipe.Type == "small" && ????);

我需要写什么而不是“??????”?或者我应该尝试使用 LINQ 查询而不是 lambda 表达式?

更新:
在“选择”子句中,我想只选择食谱及其外来成分,而不选择常规成分,尽管它们可能也有?

所以:

我应该这样走,对吧?

.Select(recipe => new { recipeName = recipe.Name, recipeIgredients = recipe.Ingredients.Where(ing => ing.Type == "exotic" });

【问题讨论】:

    标签: c# linq entity-framework


    【解决方案1】:
    var smallExoticRecipes = contex.Recipes.Include("Ingredients").Where(recipe => recipe.Type == "small" && recipe.Ingredients.Any(i => i.type == "exotic"));
    

    当然,为了清楚起见,您可能希望将其分开:

    Func<Recipe, bool> hasExoticIngredients = r => r.Ingredients.Any(i => i.type == "exotic");
    var smallExoticRecipes = context.Recipes.Include("Ingredients").Where(recipe => recipe.Type == "small" && hasExoticIngredients(recipe));
    

    另一种选择是:

    Func<Recipe, bool> hasExoticIngredients = r => r.Ingredients.Any(i => i.type == "exotic");
    Func<Recipe, bool> isSmallAndExotic = r => recipe => recipe.Type == "small" && hasExoticIngredients(recipe)
    var smallExoticRecipes = context.Recipes.Include("Ingredients").Where(isSmallAndExotic);
    

    【讨论】:

      【解决方案2】:
      var smallExoticRecipes = contex.Recipes.Include("Ingredients").Where(recipe => recipe.Type == "small" && ingredients.Any( ingredient => ingredient.recipeid == recipe.id && ingredient == "exotic"));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-22
        • 1970-01-01
        • 1970-01-01
        • 2018-02-13
        • 1970-01-01
        • 1970-01-01
        • 2014-10-02
        相关资源
        最近更新 更多