Select N+1 in the same request

Select N + 1 is a data access anti-pattern where the database is accessed in a suboptimal way.This alert in essence is a combination of the classical N+1 with the more than one session per request alerts.

Take a look at this code sample, then we'll discuss what is going on. Say you want to show the user all comments from all posts so that they can delete all of the nasty comments. The naive implementation would be something like:

var posts = Dao.GetRecentPosts(); 
foreach(var post in posts) 
{ 
       post.Comments = Dao.GetCommentsForPost(post); 
}
public IEnumerable<Post> GetRecentPosts()
{
    using(var session = sessionFactory.OpenSession())
    {
        return (from post in session.Query<Post>()
            orderby post.PublishedDate descending
            select post)
            .Take(50)
            .ToList();
    }
}
public IEnumerable<Comment> GetCommentsForPost(Post post)
{
    using(var session = sessionFactory.OpenSession())
    {
        return (from comment in session.Query<Comment>()
            where comment.Post.Id = post.Id
            select comment)
            .ToList();
    }
}

In this example, we can see that we are opening a session and loading a list of posts (the first select) and then for each of the posts that we loaded, we open up a new session, including a new connection to the database, and make an additional query.

Because we are using multiple sessions in this fashion, we can't really take advantage of NHibernate features that are meant to deal with this exact situation. The first step is to avoid using more than one session per request, and the next step is to follow the guidance on solving select N+1 problems for NHibernate.