0

Error

LINQ to Entities does not recognize the method 'Boolean ContainsAny(System.String, System.String[])' method, and this method cannot be translated into a store expression.

Code

var predicate = FilterClients(clientRequest);
clients = db.Clients.Where(predicate).Include(x => x.Organization) 
.Include(x => x.Department).ToList();

private Expression<Func<Client, bool>> FilterClients(ClientRequest clientRequest)
{
   var predicate = PredicateBuilder.True<Client>();

   if (clientRequest.IsBySearchPatternFullName)
   {
      var searchPatternFullName = clientRequest.SearchPatternFullName.Trim();
      var matches = Regex.Matches(searchPatternFullName, @"\w+[^\s]*\w+|\w");
      var words = new List<string>();
      foreach (Match match in matches)
      {
         var word = match.Value;
         words.Add(word);
      }
      var wordArray = words.ToArray();
      predicate = predicate.And(x => x.LastName.ContainsAny(wordArray) || x.FirstName.ContainsAny(wordArray) || x.MiddleName.ContainsAny(wordArray));
   }
   return predicate;
}

There is similar question C# LINQ to Entities does not recognize the method 'Boolean'

But I would like to optimize this part somehow

 predicate = predicate.And(x => x.LastName.ContainsAny(wordArray) || x.FirstName.ContainsAny(wordArray) || x.MiddleName.ContainsAny(wordArray));

Any clue people?

NoWar
  • 36,338
  • 80
  • 323
  • 498
  • Possible duplicate of [C# LINQ to Entities does not recognize the method 'Boolean'](https://stackoverflow.com/questions/20022250/c-sharp-linq-to-entities-does-not-recognize-the-method-boolean) – NoWar Nov 17 '17 at 03:13
  • Related posts - [LINQ to Entities does not recognize the method](https://stackoverflow.com/q/7259567/465053) & [Entity Framework Specification Pattern Implementation](https://stackoverflow.com/q/2352764/465053) – RBT Mar 01 '19 at 11:31
  • Another related post - [LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression](https://stackoverflow.com/q/5899683/465053) – RBT Mar 01 '19 at 11:31

2 Answers2

0

Oh! I just did it!

foreach (Match match in matches)
{
   var word = match.Value;                   
   predicate = predicate.And(x => x.LastName.Contains(word) || x.FirstName.Contains(word) || x.MiddleName.Contains(word));
}
NoWar
  • 36,338
  • 80
  • 323
  • 498
0

You can query against list of word in following way :

 predicate = predicate.And(x => wordArray.Contains(x.LastName) || wordArray.Contains(x.FirstName) || wordArray.Contains(x.MiddleName));
Akash KC
  • 16,057
  • 6
  • 39
  • 59