开发者

Build dynamic linq to Sql lambda expression

开发者 https://www.devze.com 2023-02-25 16:04 出处:网络
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

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 t开发者_开发问答his 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.


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();

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号