0

Adding all expressions inside the loop as OR condition to the IQueryable object

I have a database table and I want to check whether there is a name within the keywords given by the user from the names in the table.

For example; Database table name: Users Column names: Id, Name The data inside is: (Id:1, Name:Tom), (Id:2, Name: John), (Id:3, Name: Harry)

And the keywords from the user: "to" and "harr" Values ​​that should return: Tom and Harry

The code I tried:

var queryableUsers = db.Users.AsQueryable();
queryableUsers = queryableUsers .Where(x => values.Any(v => x.Name.ToLower().Contains(v)));

But here I am getting error:

.Name.ToLower().Contains(v)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'.

Here is what I want to do:

Expression<Func<User, bool>> predicate = (User) => false;
foreach(var v in values)
    predicate = predicate.Or(x => x.Name.Contains(term));

But Or is not working. How do I make this possible in c#?

  • You can use extension method [FilterByItems](https://stackoverflow.com/a/67666993/10646316) and write the following: `queryableUsers = queryableUsers.FilterByItems(values, (x, v) => x.Name.ToLower().Contains(v), true);` – Svyatoslav Danyliv Sep 23 '22 at 10:46
  • How you pass your keywords? In single string or List of strings? – Kiran Joshi Sep 23 '22 at 12:11
  • Assuming your `Users` table is not a list of strings, your lambda is trying to translate to SQL a query that checks if a lowercase name contains a user. You need to compare like types. Probably apply transformations (ToLower) outside the query as well. Create a list/hashtable of names to search called `namesToSearch` then `queryableUsers.Where(x => namesToSearch.Contains(x.Name));` – BurnsBA Sep 23 '22 at 13:47

0 Answers0