views:

79

answers:

2

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 instead 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" });
+1  A: 
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);
David Morton
A: 
var smallExoticRecipes = contex.Recipes.Include("Ingredients").Where(recipe => recipe.Type == "small" && ingredients.Any( ingredient => ingredient.recipeid == recipe.id && ingredient == "exotic"));
Stan R.