0

I already had a look at the following question, but it didn't gian much traction and the problem remains unsolved. How to combine (OR) two expression trees

How do you or-concatenate two Expression<Func<T, bool>>.

let's consider the simplest case:

var fulltext = "some text";

private Expression<Func<User, bool>> FulltextSearch(string fulltext) {

    Expression<Func<User, bool>> left = t => t.Name.Contains(fulltext)
    Expression<Func<User, bool>> right = t => t.Description.Contains(fulltext)
    return Expression.Lambda<Func<Task, bool>>(Expression.Or(left.Body, right.Body), left.Parameters);
}

var users = dbContext.Users
    .Where(FulltextSearch("name xy"))
    .ToList();

this is a simplified example!

This ends in an error

System.InvalidOperationException: The LINQ expression 'DbSet<User>()
    .Where(t => t.Name.Contains(__fulltext_0) | t.Description.Contains(__fulltext_0))' 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'...

But you can easily write this query like this and it works:

var users = dbContext.Users
    .Where(u => u.Name.Contains(fulltext) || u.Description.Contains(fulltext))
    .ToList()

So how do you combine two Expression<Func<T,bool>> into one such that ef core can translate it into SQL?

Isitar
  • 1,286
  • 12
  • 29
  • And what problem(s) did you have using the solutions provided on the question you linked? – Servy Aug 23 '21 at 16:22

1 Answers1

2

Expression.Or will translate to a bitwise ORoperation (c# | Operator). https://learn.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression.or?view=net-5.0
This will lead to the InvalidOperationException since it cannot be translated to SQL.

Expression.OrElse will translate to a logical ORoperation. (c# || operator) https://learn.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression.orelse?view=net-5.0
This translates to SQL's OR operator and is the one you want to use when combining the expressions.

fvetsch
  • 181
  • 1
  • 11