Reputation: 4557
Question: Given an NHibernate entity Parent, is there any way to get a LINQ query on a Children collection to execute on the database side rather than lazy-loading all the children and then performing the query?
Scenario:
Parent object has IList collection (Children)
var parent = _parentRepository.Get(parentId); //loads parent
..do stuff
//this causes all Child objects to be loaded into memory
//and then finds the subset of boy objects (not great performance)
var boys = parent.Children.Where(t => t.Sex == 1);
If I try explicitly passing an Expression<Func<Child, bool>>
, I get an error that it's expecting a type Func<Child, bool>
.
Is there any way to get more efficient lazy loading w/NHibernate?
Thanks!
Upvotes: 0
Views: 625
Reputation: 109119
Recommended practice in NHibernate is to keep a session short-lived ans thus prevent lazy loading. You can improve the efficiency of your query by applying "join fetch" (refer to the NHibernate documentation), which, by the way, will also read all child objects, but in one shot and not in the infamous 1 + N anti pattern.
Children
is not an IQueryable
so you can't use an expression. Linq to NHibernate would allow you to query a Session with linq statements that get translated into sql. Then you could query the Children collection with expressions as predicates.
Upvotes: 2