具有嵌套关系条件的 Linq to NHibernate 表达式树

发布于 2024-11-17 08:57:46 字数 687 浏览 7 评论 0原文

在我使用 NHibernate 的 .Net 项目中,我有一段代码根据用户在 UI 中的过滤器中设置的值构建表达式树列表。 该表达式是针对我的域模型的特定对象(比如说客户)构建的。 当我想为 Customes 的属性创建过滤条件时,一切都很好,如下例所示:

Expression<Func<Model.Customer, bool>> expr = c =>
                    c.Name == "My Company";

但是现在,我需要创建一个表达式,让我可以根据涉及一对多关系的条件过滤客户...就说订单吧。一个客户可以有多个订单,因此关系是一对多的。我需要构建一个可以应用于客户查询的表达式,以便仅提取在 2010 年至少下了一个订单的客户。我会写这样的内容:

Expression<Func<Model.Cusotmer, bool>> expr = c =>                        
                    c.Orders.Where(o => o.year == 2010).Count() > 0;

太糟糕了,这不起作用。 NHibernate 似乎无法解析这个表达式。 关于如何编写实现该搜索条件并可由 Linq 2 NHibernate 解析的表达式树有什么想法吗?

In a .Net project in which I'm using NHibernate, I have a piece of code that build a list of expression trees depending on the values set in the filter by the user in the UI.
The expression is build against a specific object of my domain model, let's say Customer.
When I wanna create a filter criteria for a property of Customes, everything's fine, like in the following example:

Expression<Func<Model.Customer, bool>> expr = c =>
                    c.Name == "My Company";

But now, I need to create an expression that let me filter che customer based on a condition involving a one to many relation... let's say Order. A customer can have many orders, so the relationship is one-to-many. I need to build an expression that I can apply to a Customer query, in order to exptract only the customers which have at least one order placed in 2010.I'd write something like this:

Expression<Func<Model.Cusotmer, bool>> expr = c =>                        
                    c.Orders.Where(o => o.year == 2010).Count() > 0;

Too bad this won't work. It seems that NHibernate is not able to parse this Expression.
Any idea on how to write an expression tree that implement that search criteria and is parsable by Linq 2 NHibernate?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

月下凄凉 2024-11-24 08:57:46

因为你使用 Count() > 0 你可以使用 Any 代替:

Expression<Func<Model.Cusotmer, bool>> expr = c =>                        
                    c.Orders.Any(o => o.year == 2010);

because you use Count() > 0 you can use Any instead:

Expression<Func<Model.Cusotmer, bool>> expr = c =>                        
                    c.Orders.Any(o => o.year == 2010);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文