Build dynamic linq to Sql lambda expression

expression-trees lambda linq linq-to-sql

Question

I am currently looking for a way where I can build a lambda expression for my Linq to SQL query based on user input at runtime. I have been looking around on the net, but can't find anything that is useful. If anyone can show me how to do this or there is any good articles, please do let me know. Much appreciated!

Example:

Let's say I have this Linq query:

var loc = (from l in Entity.Locations
           select l).Where(a => a.LocationId > 5);

Can this expression a => a.LocationId > 5 be built at runtime? Depending on whether the user has chosen LocationId. If the user has chosen Name then it would be a => a.Name == "bla".

I have come across an article from Scott but I would prefer a solution that allows me to create a strongly type expression which I can detect any possible errors at compile time.

Any information would be much appreciated.

Thanks.

Accepted Answer

You can create new LINQ expressions containing old expressions.

var loc = (from l in Entity.Locations select l);

if (hasLocation)
    loc = loc.Where(a => a.LocationId > 5);

if (hasName)
    loc = loc.Where(a => a.Name == "bla");

etc.

The expression is only evaluated once you use it, like var result = loc.ToList();




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why