Building dynamic linq for lambda Sql expression

I'm currently looking for a way that I can build a lambda expression for my Linq to SQL query based on user input at runtime. I searched the net but cannot find anything useful. If anyone can show me how to do this, or have some good articles, please let me know. Really appreciate!

Example:

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 run time? Depending on whether the user has selected LocationId. If the user a => a.Name == "bla" name, it will be a => a.Name == "bla" .

I came across Scott's article, but I would prefer a solution that allows me to create a strict type expression that I can detect during compilation of any possible errors.

Any information would be highly appreciated.

Thanks.

+4
source share
1 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"); 

and etc.

An expression is evaluated only after its use, for example var result = loc.ToList();

+2
source

Source: https://habr.com/ru/post/1348041/


All Articles