NHibernate Pitfalls: QueryOver and Deep Expressions
This is part of a series of posts about NHibernate Pitfalls. See the entire collection here.
When using the QueryOver API, unlike LINQ, when applying restrictions, you only have access to direct properties of the target entity type. If you need to access deeper nested properties – those from associated entities – you have to explicitly join. This does not apply to the property representing the foreign key, however. Let’s see an example:
1: //this will not work
2: session.QueryOver<Order>().Where(x => x.Customer.Name == "Some Name").List();
3:
4: //this will work
5: session.QueryOver<Order>().JoinQueryOver(x => x.Customer).Where(x => x.Name == "Some Name").List();
6:
7: //this will also work because Id is the foreign key
8: session.QueryOver<Order>().Where(x => x.Customer.Id == CustomerId).List();
In general, the QueryOver API is more complex to use than the LINQ one, the advantage is that it allows better composition of dynamic queries.