I have been searching a lot about my current problem but I could not find a real answer to solve that issue.
I am trying to build a LINQ Query that produces the following SQL:
SELECT * FROM TABLE WHERE (Field1 = X, Field2 = Y ... ) or (Field3 = Z)
In a normal situation I would just do this:
Object.Where(c => (c.Field1 == X && c.Field2 == Y) || (c.Field3 == Z))
I cannot use this approach because the query is build by using multiple .Where()
calls.
Having an example:
// This is a short example, the real world situation has 20 fields to check and they are all connected with an AND.
if (model.Field1.HasValue)
{
Query = Query.Where(c => c.Field1 == X)
}
if (model.Field2.HasValue)
{
Query = Query.Where(c => c.Field2 == X)
}
[...] like 20 more of these .Where() calls.
and that is how it gets complicated for me. All these .Where()
calls are building a Linq Query that is connected with AND
, which is fine.
How do I let them execute with Parenthese and add a simple OR
now using the API?
Is there a way to save the predicate in some variables so I can make something like:
Query = Query.Where(c => previousPredicates || c.Field3 == X)
or how to solve that problem?
I think there must be a good solution for that particual problem and I am not the only one who needs it, but I am absolute unsure how to achieve it.
P.S: I can't really remove the multiple .Where()
calls and writing direct SQL is neither an option.
EDIT
StackOverflow wants me to say why my question is different from others. Well, the thing is about Parentheses
. I do not want to connect all .Where()
with a single OR clause, I want to leave them with AND
and add another OR
clause while all the AND
queries are being parenthesied.
someOtherCondition
is the expression that may contain severalAND
s. TheseAND
blocks are then graduallyOR
ed together.||
with&&
. Then you can do exactly what you wantQuery = Query.Where(c => previousPredicates || c.Field3 == X)
Query = Query.Where(c => c.Field1 ?? X == X && c.Field2 ?? X == X)
. If it is entity framework query, add tag because some cases are not applicable