Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a pattern using Linq to dynamically create a filter?

Tags:

Is there a pattern using Linq to dynamically create a filter?

I have the need to create custom filtering on a list, in the past I would just dynamically create the SQL...it doesn't seem like this is possible with Linq.

like image 393
emcpadden Avatar asked Aug 27 '08 18:08

emcpadden


People also ask

What is Dynamic Linq?

The Dynamic LINQ library exposes a set of extension methods on IQueryable corresponding to the standard LINQ methods at Queryable, and which accept strings in a special syntax instead of expression trees.

What is the LINQ query operator used to filter data?

Filtering operators are those operators which are used to filter the data according to the user requirement from the given data source or from the given sequence. For example, in an employee record, we want to get the data of the employees whose age in 21.

Is Dynamic Linq safe?

And Dynamic Linq is actually composed from strings, therefore it is potentially prone to attack by injection. Obviously, the attacker will have to be aware of the fact that you are using DynamicLinq and could attack only preparing the data so it results in valid malicious Dynamic Linq query.


1 Answers

Check out the Dynamic Linq Library from ScottGu's blog:

For example, below is a standard type-safe LINQ to SQL VB query that retrieves data from a Northwind database and displays it in a ASP.NET GridView control:

Dim Northwind As New NorthwindDataContext Dim query = From q In Northwind.Products Where p.CategoryID = 2 And p.UnitPrice > 3 Order By p.SupplierID Select p  Gridview1.DataSource = query GridView1.DataBind() 

Using the LINQ DynamicQuery library I could re-write the above query expression instead like so

Dim Northwind As New NorthwindDataContext Dim query = Northwind.Products .where("CategoryID=2 And UnitPrice>3") . OrderBy("SupplierId") Gridview1.DataSource = query GridView1.DataBind() 

Notice how the conditional-where clause and sort-orderby clause now take string expressions instead of code expressions. Because they are late-bound strings I can dynamically construct them. For example: I could provide UI to an end-user business analyst using my application that enables them to construct queries on their own (including arbitrary conditional clauses).

like image 186
Geoff Avatar answered Nov 09 '22 00:11

Geoff