Book Image

Learning NHibernate 4

Book Image

Learning NHibernate 4

Overview of this book

Table of Contents (18 chapters)
Learning NHibernate 4
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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)
...