开发者

How to write a LINQ query or Lambda expression on one to many relation with filter

I was thinking how to write a proper LINQ query or lambda expression on one to many relation while do a proper filtering of the entity on the "many" side for Entity Framework.

So two entities are:

Recipe

id

name type [small|big]

Ingredient

id

recipeId

name

type [regular|exotic]

So how to write a LINQ query that selects recipes that are small and have exotic ingredients?

It could go like:

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

What do I need to write i开发者_Go百科nstead of "????"? Or I should try with LINQ query instead of lambda expression?

UPDATE:

In "Select" clause I would like to select only recipes and its exotic ingredients without regular ones although they might also have?

So:

I should go like this, right?

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


var smallExoticRecipes = contex.Recipes.Include("Ingredients").Where(recipe => recipe.Type == "small" && recipe.Ingredients.Any(i => i.type == "exotic"));

Of course, you may want to divide this out for clarity:

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));

Another option is:

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);


var smallExoticRecipes = contex.Recipes.Include("Ingredients").Where(recipe => recipe.Type == "small" && ingredients.Any( ingredient => ingredient.recipeid == recipe.id && ingredient == "exotic"));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜