我正在考虑如何在一对多关系上编写正确的LINQ查询或lambda表达式,同时在Entity Framework的“多”方面对实体进行适当的过滤。
所以两个实体是:
配方
ID
名称
输入[small | big]
成分
ID
recipeId
命名
输入[常规|异国情调]
那么如何编写一个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" });
答案 0 :(得分:2)
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);
答案 1 :(得分:0)
var smallExoticRecipes = contex.Recipes.Include("Ingredients").Where(recipe => recipe.Type == "small" && ingredients.Any( ingredient => ingredient.recipeid == recipe.id && ingredient == "exotic"));