【问题标题】:Entity Framework search for recipes with an array of ingredients [duplicate]实体框架搜索具有一系列成分的食谱[重复]
【发布时间】:2023-03-03 06:08:24
【问题描述】:

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

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

【问题讨论】:

  • But what if I the search string needs to be multiple ingredients at a time. 假设您选择了 15 种成分。食谱是否需要使用其中一种成分? 15? 1个或更多?还有什么?
  • 配方需要其中一种成分,并且用户需要指定一种或多种
  • recipes = db.Recipes.Where(r =&gt; r.Ingredients.Any(i =&gt; yourListContainingIngredientsTheySelected.Contains(i.IngredientName)); 这能满足您的需求吗?
  • 它确实返回了想要的结果!谢谢你好先生。

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


【解决方案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.
        }

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

【讨论】:

  • 如果searchStrings.Length为15,会执行多少条SQL?
  • 我很确定 Entity Framework 将语句连接成尽可能少,但我可能弄错了。您可以随时打印出结果查询以供自己查看。
  • 它将运行 15 个查询
  • 是的。我现在看到了,回头看。 XD
猜你喜欢
  • 1970-01-01
  • 2016-10-01
  • 2011-11-08
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多