LINQ to EF - search for entries where the row property of the child collection at least partially matches all entries in the row list

I am currently writing a recipe web application using LINQ and Entity Framework 5.0. I am struggling a bit with this request, so any help is greatly appreciated!

There will be a search function in which users can enter a list of ingredients for which they want the recipe results to match. I need to find all recipes in which the associated collection of ingredients (the name property) contains the text of each entry in the string list (user search terms). For example, consider the following two recipes:

Tomato Sauce: Ingredients 'crushed tomatoes', 'basil', 'olive oil'
Tomato Soup:  Ingredients 'tomato paste', 'milk', 'herbs

If the user used the search terms “tomato” and “oil”, he returned the tomato sauce, but not the tomato soup.

var allRecipes = context.Recipes
                .Include(recipeCategory => recipeCategory.Category)
                .Include(recipeUser => recipeUser.User);

IQueryable<Recipe> r = 
from recipe in allRecipes
let ingredientNames = 
    (from ingredient in recipe.Ingredients 
     select ingredient.IngredientName)
from i in ingredientNames
let ingredientsToSearch = i where ingredientList.Contains(i)
where ingredientsToSearch.Count() == ingredientList.Count()
select recipe;

I also tried:

var list = context.Ingredients.Include(ingredient => ingredient.Recipe)
       .Where(il=>ingredientList.All(x=>il.IngredientName.Contains(x)))
       .GroupBy(recipe=>recipe.Recipe).AsQueryable();

Thanks for the help!

+5
1

-

public IEnumerable<Recipe> SearchByIngredients(params string[] ingredients)
{
    var recipes = context.Recipes
                .Include(recipeCategory => recipeCategory.Category)
                .Include(recipeUser => recipeUser.User);
    foreach(var ingredient in ingredients)
    {
        recipes = recipes.Where(r=>r.Ingredients.Any(i=>i.IngredientName.Contains(ingredient)));
    }

    //Finialise the queriable
    return recipes.AsEnumerable();

}

, :

SearchByIngredients("tomatoes", "oil");

var ingredients = new string[]{"tomatoes", "oil"};
SearchByIngredients(ingredients );

, , - . where AND SQL ( , ). Linq , , queriable, , , , .

: / , .

+6

All Articles