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()) { var employees = Database.Session.Query<Employee>() .Where(e => e.ResidentialAddress.City == "London"); foreach (var employee in employees) { foreach (var benefit in employee.Benefits) ...