I've been googling but haven't found any good info on building a good search function in a ASP.NET MVC project.
Off the top of my head, a search feature for searching authors and books would look like this:
char[] delimiterChars = { ' ', ','};
string[] searchterms = SearchBox.Split(delimiterChars);
IQueryable<SearchResult> SR = _db.Books.Where(e =>
(e.Title.Contains(SearchTerm[0]) || e.Author.Name.Contains(SearchTerm[0]))
&& (e.Title.Contains(SearchTerm[1]) || e.Author.Name.Contains(SearchTerm[1]))
//&& repeat for as many words were entered in the search box
)
.Select(e => new SearchResult
{
Title = e.Title,
Type = "Book",
Link = "Book/" + e.BookID
});
Questions
- Is there a better way of doing this?
- If not, how can I dynamically construct my SQL query to look for as many search terms as were entered?
- Can I append search results from a second search to the
SR
variable?
Other Considerations
In the search above I am searching for results that match the Book or Author. Maybe immediately after I want to do a search just looking for a match in the Author table, and then append those results to the SR
variable results from the first query. I don't know if that's the most practical approach, but can it be done?