实体框架搜索具有一系列成分的食谱

时间:2017-12-11 12:22:00

标签: c# asp.net-mvc entity-framework search

我有一个搜索,它返回所有食谱,其中至少有一种成分与搜索字符串相匹配

recipes = db.Recipes.Where(r => r.Ingredients.Any(i => i.IngredientName.Contains(searchString)));

用户在视图中输入搜索字符串

@using (Html.BeginForm())
{ <p> Find by name: @Html.TextBox("SearchString") <input type="submit" value="Search" /></p> }

但是,如果我的搜索字符串一次需要多个成分,那该怎么办呢。

我尝试将字符串拆分为数组。制作和SQL连接以获取配方列表及其包含的成分。但我不知道该怎么做。

public ViewResult Index(string sortOrder, string[] FilteredsearchString, string searchString)
        {
            FilteredsearchString = searchString.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);

            // "string" can be lowercase.
            Console.WriteLine(string.Join(",", FilteredsearchString));

            // ... "String" can be uppercase.
            Console.WriteLine(String.Join(",", FilteredsearchString));

            IQueryable recipes;
            if (String.IsNullOrEmpty(searchString))
            {
                recipes = db.Recipes;
            }
            else
            {
                var Allrecipes = db.Database.SqlQuery<string>(
                         "SELECT * FROM Recipes" +
                         "INNER JOIN RecipeIngredient ON Recipes.RecipeID = RecipeIngredient.RecipeRefID " +
                         "INNER JOIN RecipeIngredient.IngredientRefID = Ingredients.IngredientID " +
                         "WHERE Ingredients.IngredientName IN ()").ToList();

                recipes = from r in Allrecipes where FilteredsearchString.Contains("Ingredient.IngredientName");
            }
            return View(recipes);
        }

1 个答案:

答案 0 :(得分:-1)

我可能只是在一个循环中将它们连接在一起。

        string[] searchStrings = new string[0]; // Your array of search terms.
        List<Recipe> recipes = new List<Recipe>(); // A list to store the results.
        for (int i = 0; i < searchStrings.Length; i++) // Loop through all the search keywords
        {
            recipes.AddRange(db.Recipes.Where(r => r.Ingredients.Any(i => i.IngredientName.Contains(searchStrings[i])))); // Add all recipes that match.
        }

您当然必须确保自己没有任何重复结果。 :)