构建动态 linq to Sql lambda 表达式
我目前正在寻找一种方法,可以根据运行时的用户输入为 Linq to SQL 查询构建 lambda 表达式。我一直在网上四处寻找,但找不到任何有用的东西。如果有人可以告诉我如何做到这一点或者有任何好的文章,请告诉我。非常感谢!
示例:
假设我有这个 Linq 查询:
var loc = (from l in Entity.Locations
select l).Where(a => a.LocationId > 5);
Can this expression a =>; a.LocationId> 5
在运行时构建?取决于用户是否选择了LocationId。如果用户选择了名称,那么它将是 a => a.名称==“bla”
。
我看到了 Scott 的一篇文章,但我更喜欢一个解决方案,它允许我创建一个强类型表达式,我可以在编译时检测到任何可能的错误。
任何信息将不胜感激。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以创建包含旧表达式的新 LINQ 表达式。
表达式仅在使用后才会计算,例如 var result = loc.ToList();
You can create new LINQ expressions containing old expressions.
etc.
The expression is only evaluated once you use it, like
var result = loc.ToList();