4

Let's say I have a query like:

r = r.Where(x => iEnumerableMachineNames.Contains(x.Machine.Name) 
                 || x.Server==true);

Is there a way to build the predicate (I think that's what it's called) outside of the statement, for instance

t = (x => iEnumerableMachineNames.Contains(x.Machine.Name));
s = (x => x.Server==true)
q = t.Or(s);
r = r.Where(x => q);

Basically I want to programmatically build my query based on input parameters, for EF 5.

1 Answer 1

1

You can build expressions dynamically but not as simply as your pseudo code - it requires reflection and expression trees (read this).

A simple way to accomplish what it seems like you'd like to do is to short circuit different parts of the predicate using boolean flags:

bool testMachineName;
bool testIsServer;

r = r.Where( x =>
    ( !testMachineName || iEnumerableMachineNames.Contains( x.Machine.Name ) ) ||
    ( !testIsServer || x.Server ) );
Sign up to request clarification or add additional context in comments.

3 Comments

Would that work with EF or would it complain about not being able to construct that query? I guess I'll try it... :-)
Actually that doesn't work and returns everything right? If testMachine is false it's (true || whatever) == true and returns everything... Or am I going crazy?
that's why it's !testXyz - if you want a specific test, the expression will evaluate to false and force the remainder of the boolean expression to evaluate. If you don't want to test for x.Server == true, then you set testIsServer = false and that evaluates to true, thereby not filtering out items that are !x.Server

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.