Stack Exchange
Querying EF DB using multiple input parameters from Web API
I have a simple Web API action with multiple input parameters:
MethorA(string val1, string val2, int val3, int val4){}

Where multiple parameters could be optional:
MethorA(string val1, string val2 = null, int val3 = null, int val4 = null){}

And I am using these parameters as a complex expression to query the DB using EF.
So I built several sub-expressions, like this:
Expression<Func<A, bool>> predicate1 = x=> x.f1 ==val1;
Expression<Func<A, bool>> predicate2 = x=> x.f2 ==val2;
Expression<Func<A, bool>> predicate3 = x=> x.f3 ==val3;
Expression<Func<A, bool>> predicate4 = x=> x.f4 ==val4;

Now I need to construct a single predicate which I could pass to my data access layer which accepts something like this:
context.Entity.FilterBy(Expression<Func, bool> predicate);

And this is a where I am stucked. How can I combine all together all the predicates: predicate1,2,3,4 ?
I googled, found that there is Expression.OrElse but not sure how to properly use it and it accepts only 2 predicates. I thought I could use it like this:
var total = Expression.OrElse(predicate1, predicate2);
total = Expression.OrElse(total, predicate3);
total = Expression.OrElse(total, predicate4);

But it does not work.

I'm linking another answer rather than marking as duplicate because I don't know if this actually solves the problem, but have you considered a Predicate Builder? https://stackoverflow.com/questions/51720429/predicate-build-with-net-core-and-ef-core

Do you want them as And or Or?

You can do this:
Expression<Func<A, bool>> predicate1 = x=> x.f1 == val1;
Expression<Func<A, bool>> predicate2 = x=> x.f2 == val2;
Expression<Func<A, bool>> predicate3 = x=> x.f3 == val3;
Expression<Func<A, bool>> predicate4 = x=> x.f4 == val4;

var body = Expression.Or(predicate1.Body, predicate2.Body);
var lambda = Expression.Lambda<Func<A, bool>>(body, predicate2.Parameters[0]);

body = Expression.Or(lambda.Body, predicate3.Body);
lambda = Expression.Lambda<Func<A, bool>>(body, predicate3.Parameters[0]);

body = Expression.Or(lambda.Body, predicate4.Body);
var finalExpression = Expression.Lambda<Func<A, bool>>(body, predicate4.Parameters[0]);

You can pass finalExpression to the filter.
If you want to use And instead of Or, Just replace Or method with And
