0

When I want to use Any() expression in the Where() filtering that I send to the database, I get the following exception.

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'.

If I filter with Where() after getting all the records from the database it works correctly. But I want to get filtered data from database.

My codes that I got the exception are as follows.

var firstList = await _firstRepository
                     .FilterByAsync(x => x.IsActive);

var secondList = await _secondRepository
                       .FilterByAsync(x => !firstList
                                           .Any(y =>
                                                y.CategoryId == x.CategoryId &&
                                                y.Type == x.Type)
                                      );

Note : There are 2 different repositories as the queries have to go to 2 different tables.

Also, I have a filter method inside my generic repository.

public async Task<List<TEntity>> FilterByAsync(Expression<Func<TEntity, bool>> predicate)
{
    return await _entities.Where(predicate).ToListAsync();
}

I hope I have expressed my problem well.

Thanks in advance for the answers.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • 1
    Use `Contains` instead of `Any` – Mong Zhu Apr 22 '22 at 14:48
  • I can't check if there is a secondEntity in the firstEntity list with Contains(). – burakkorman Apr 22 '22 at 15:01
  • Chain AsEnumerable() before the call to filterAsync, if you don’t mind it being evaluated client side. Else you need to use contain, firstordefault or .count – Lee Apr 22 '22 at 15:12
  • 1
    There is no out of the box support for this in EF (only for single property using `Contains` - `var idList = new List...; ...Where(e => idList.Contains(e.Id)))`. For multiple properties you need either use `Union` in cycle, or build predicate `Expression` manually or via 3rd party library. – Guru Stron Apr 22 '22 at 15:19

0 Answers0