C
C#9mo ago
nox7

EF Core - Runtime-Based "OR" "AND" Comparison in Where()

I am allowing users on a web application to create filters on a queried table. It will generate an array of "filters" in defined order. They will be able to define if the next comparison is connected to the previous via "OR" or "AND" On the back-end, I will iterate over each "Filter" in the array of filters, adding more .Where() calls to the IQueryable. However, how can I make create an IQueryable that can properly chain these filters so that they are concatenated by "OR" or "AND" appropriately from the previous filter? E.g. User submits two filters for two columns. They could be linked as Column1 = "ss" OR Column2 = "DD" Or they could submit it as Column1 = "ss" AND Column2 = "DD"
6 Replies
Denis
Denis9mo ago
You might have to generate LINQ Expressions for this, and they are not pretty. These expressions allow you to combine objects to define an expression and then you can compile it during runtime into an invocable delegate like Action or Func.
Denis
Denis9mo ago
Expression Class (System.Linq.Expressions)
Provides the base class from which the classes that represent expression tree nodes are derived. It also contains static (Shared in Visual Basic) factory methods to create the various node types. This is an abstract class.
Denis
Denis9mo ago
Please verify whether this works with ef core, I'm not certain I'm using these LINQ Expressions for filtering locally accessible data.
nox7
nox7OP9mo ago
Thanks for the resource - I'll take a look and test it out.
Denis
Denis9mo ago
Or actually it might work. Ef core linq takes in an expression as a parameter. So essentially, you don't compile it and supply it directly. Ef core will then compile it accordingly into the respective SQL
nox7
nox7OP9mo ago
Late update on this, but yes it worked as described - I was able to create dynamic query filters with expression objects.
Want results from more Discord servers?
Add your server