0

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!

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, that's what I was afraid of - was hoping someone more clever than I had designed a more efficient approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.