构建动态 linq to Sql lambda 表达式

发布于 2024-11-01 18:16:23 字数 527 浏览 6 评论 0原文

我目前正在寻找一种方法,可以根据运行时的用户输入为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

听闻余生 2024-11-08 18:16:23

您可以创建包含旧表达式的新 LINQ 表达式。

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

表达式仅在使用后才会计算,例如 var result = loc.ToList();

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文