Taha Attique
Taha Attique

Reputation: 23

Entity Framework, Linq query is throwing exception "could not be translated. Either rewrite the query in a form that can be translated

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

enter image description here

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

Answers (1)

Alexander Petrov
Alexander Petrov

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

Related Questions