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?
because you use
Count() > 0you can use Any instead: