Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically generate LINQ queries

Tags:

c#

xml

linq

We have an object

public class SomeObject {    public Name {get;set;}    public City {get;set;}    public State {get;set}    //various other parameters.  Let's say there's ~20 } 

Is it possible to dynamically create new LINQ queries without recompilation of source code? Instead, the query parameters come from an XML structure that is stored and updated in the database.

var result = from i in someObj              where               //XML requests Name = 'Bob'...so append this where clause              name = 'Bob' 

Can this be done?

like image 915
P.Brian.Mackey Avatar asked Feb 29 '12 19:02

P.Brian.Mackey


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.

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.

Which is better lambda or LINQ?

So performance-wise, there's no difference whatsoever between the two. Which one you should use is mostly personal preference, many people prefer lambda expressions because they're shorter and more concise, but personally I prefer the query syntax having worked extensively with SQL.


1 Answers

Here is a solution with expression trees:

var param = Expression.Parameter(typeof(SomeObject), "p"); var exp = Expression.Lambda<Func<SomeObject, bool>>(     Expression.Equal(         Expression.Property(param, "Name"),         Expression.Constant("Bob")     ),     param ); var query = someObj.Where(exp); 

I know it's much more complex, but this may be useful in times.

like image 189
Balazs Tihanyi Avatar answered Oct 05 '22 20:10

Balazs Tihanyi