當人們搜索我的網站時,我不想只搜索值(q),我想用空格作爲分隔符搜索每個單詞。我編寫了大部分代碼,但有些部分我不知道該怎麼做。如何使用EntityFramework爲搜索交叉多個查詢?
你可以檢查下面的代碼中的「待辦事項」,並建議我一個辦法嗎?或者可能是一個完全不同的方法順便說一句,如果可能的話,我想保留SQL代碼的一部分,因爲它對我來說更自然,但所有的TODO都可以在LINQ中完成。
感謝
下面是代碼:
[HttpPost]
public ActionResult Search(string q)
{
ViewBag.q = q;
String[] strQueries = q.Split(' ');
//TODO: Create an array of type var???
foreach (string str in strQueries)
{
var recipesTemp = db.Recipes.SqlQuery(
String.Format(
"SELECT * FROM Recipe WHERE Name LIKE '%{0}%' " +
"UNION ALL " +
"SELECT * FROM Recipe WHERE IDRecipe IN (" +
" SELECT IDRecipe FROM Subtitle WHERE Name LIKE '%{0}%') " +
"UNION ALL " +
"SELECT * FROM Recipe WHERE IDRecipe IN (" +
" SELECT IDRecipe FROM RecipeTag " +
" INNER JOIN Tag ON Tag.IDTag = RecipeTag.IDTag " +
" WHERE Name LIKE '%{0}%') " +
"UNION ALL " +
"SELECT * FROM Recipe WHERE IDRecipe IN (" +
" SELECT IDRecipe FROM Subtitle " +
" INNER JOIN Ingredient ON Ingredient.IDSubtitle = Subtitle.IDSubtitle " +
" WHERE QuantityAndName LIKE '%{0}%')", str)).Distinct().OrderBy(r => r.Name).ToList();
//TODO: Add recipesTemp to the array of var
}
var recipes = //TODO: INTERSECT the results from all the recipesTemp in the array of type var
return View("Search", recipes);
}
如果有一個「祕方」在這裏,它是一個SQL注入攻擊。 – 2013-02-21 02:46:21
除了安全問題之外,你有關於如何做到這一點的想法嗎?在這種情況下,你會建議如何避免SQL注入攻擊? – 2013-02-21 03:13:27