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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With