Reputation: 23
I am building a platform on the blazer server, Dotnet core. I am using the code-first approach in EF core using repository patterns. The problem is there are messages in the database. I have an array of strings. I have to get those messages from the database in which all the strings in the array are present.
To accomplish this, I have created the LINQ expression to send it as a filter in the EF core to get all those messages.
public Expression<Func<EmailHistory, bool>> WithSearch(string searchTerm)
{
// Here it is converting a string to a list of words by separating it on the basis of " ".
// Trim() is used to remove extra spaces
string[] listOfWords= (searchTerm.Trim()).Split(' ');
return emailHistory =>
listOfWords.All(x => emailHistory.Message.Contains(x));
}
The above expression expectedly should have returned all the message containing all the strings in the "listOfWords" array but instead it is throwing the following expection
I am unable to understand the reason that why it can't be translated and how to make this possible.
Can you help? Thanks in Advance
Upvotes: 0
Views: 268
Reputation: 14261
This can be done as follows:
public static class QueryExtensions
{
public static IQueryable<EmailHistory> Search(this IQueryable<EmailHistory> emailHistories, string searchTerm)
{
string[] words = searchTerm.Split(' ', StringSplitOptions.RemoveEmptyEntries);
var query = emailHistories;
foreach (var word in words)
{
query = query.Where(x => x.Message.Contains(word));
}
return query;
}
}
Use like this:
var query = context.EmailHistories.Search("a b c");
Upvotes: 0