Having trouble getting this to work:
/// <summary>
/// Retrieve search suggestions from previous searches
/// </summary>
public static string[] getSearchSuggestions(int SectionID, string Query)
{
string[] Suggestions;
string[] Words = Query.Split(' ');
using (MainContext db = new MainContext())
{
Suggestions = (from c in db.tblSearches
where c.SectionID == SectionID &&
Words.Any(w => c.Term.Contains(w))
select c.Term).ToArray();
}
return Suggestions;
}
I get:
System.NotSupportedException: Local sequence cannot be used in LINQ to SQL implementations of query operators except the Contains operator.
I want to return records where the field c.Term contains any of the words in the Words array. I would also like to have it ordered by the total number of matches, but that seems really hard to do! I found this MSDN. But I can’t get it to work with my query either. Also found this but it’s not working.
Ok, after plugging away enough at it I realized that the problem wasn’t the Any or the Contains. Linq to SQL doesn’t like you combining the local sequence (words) with the SQL collection (db.tblSearches). So in order to accomplish this, you have to break it out into 2 separate queries.
Keep in mind, that in the second query, the
Containsis case sensitive, so you might have to add a case-insensitive extension method or go old school and kick them.ToUpper(). I ran this in 4.0 on one of my contexts and it returned all 88 strings correctly (out of a possible 9814). Though it was a thorough PITA. Definite +1 on this question.Edit:
Added
.Distinct()to the final answer.