【发布时间】: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 => r.Ingredients.Any(i => yourListContainingIngredientsTheySelected.Contains(i.IngredientName));这能满足您的需求吗? -
它确实返回了想要的结果!谢谢你好先生。
标签: c# asp.net-mvc entity-framework search