开发者

Need advice for building a search in an ASP.NET MVC application

开发者 https://www.devze.com 2022-12-12 20:54 出处:网络
I\'ve been googling but haven\'t found any good info on building a good search function in a ASP.NET MVC project.

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

  1. Is there a better way of doing this?
  2. If not, how can I dynamically construct my SQL query to look for as many search terms as were entered?
  3. 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 o开发者_开发技巧r 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?


My first inclination would be to offload this to something like Lucene.Net. Short of that, you could do this:

char[] delimiterChars = { ' ', ','};
string[] searchterms = SearchBox.Split(delimiterChars);

var temp = _db.Books.AsQueryable();
foreach (string term in searchterms)
{ 
  temp = temp.Where(e => 
    (e.Title.Contains(term) || e.Author.Name.Contains(term));
}

IQueryable<SearchResult> results = temp.Select(e => new SearchResult
{
  Title = e.Title,
  Type = "Book",
  Link = "Book/" + e.BookID
});

Note the foreach that dynamically builds the query.

0

精彩评论

暂无评论...
验证码 换一张
取 消