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!
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.
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");
The expression is only evaluated once you use it, like
var result = loc.ToList();