Avoiding the select N+1 problem

We had briefly mentioned select N+1 problem in the previous chapter. Select N+1 is bad from both performance and memory consumption point of view. We are going to discuss how we can avoid this problem. Before we get our hands dirty, let's spend some time trying to understand what is select N+1 problem.

What is the select N+1 problem?

It is easier to understand select N+1 problem if we read it in reverse – 1+N select. That is right. Let's see how.

Suppose you want to load all employees living in London and then for every employee iterate through the benefits that they are getting. Following is one way of doing that using a LINQ query:

[Test] public void WithSelectNPlusOneIssue() { using (var transaction = Database.Session.BeginTransaction()) ...

Get Learning NHibernate 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.