Programmatically constructing a query using a LINQ statement with an entity infrastructure

Say I have a query like:

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

Is there a way to build a predicate (I think it's called) outside the instruction, for example

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.

+4
source share
1 answer

You can create expressions dynamically, but not as simple as your pseudo-code - this requires reflection trees and expressions ( read this ).

An easy way to accomplish what you like is to short circuit the various parts of the predicate using boolean flags:

bool testMachineName;
bool testIsServer;

r = r.Where( x =>
    ( !testMachineName || iEnumerableMachineNames.Contains( x.Machine.Name ) ) ||
    ( !testIsServer || x.Server ) );
+1
source

Source: https://habr.com/ru/post/1525706/


All Articles