EFCore Filter on Property With Contains And List of Values

Viewed 893

I am trying to filter entities based on a list of search values within specific fields on the entity.

For example:

var searchValues = new List<string> { "abc", "xyz" };
var posts = Context.Posts
    .Where(p => searchValues.Any(v => p.Title.Contains(v)))
    .ToList();

This generates an exception "The LINQ expression 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'.

What is the correct way to apply contains filters with multiple search values?

1 Answers

If you convert Posts to list before the where it should work.

var posts = Context.Posts.ToList()
.Where(p => searchValues.Any(v => p.Title.Contains(v)));

That way the filter doesn't have to be translated into SQL (or whatever db you're using).

The catch is that all of the Posts data will be loaded into memory to make the list. This may or may not be acceptable depending on the quantity of Posts and database calls.

Related