NHibernate Eager Loading Retrieving Duplicate Results

by Michael Henstock 31. January 2014 08:29

Recently, I had created a query for an entity while attempting to eager load 2+ child lists using NHibernate. Eager loading a single child list was working correctly, however, when I started to attempt to eager load 2 or more child lists, all of the child lists would end up with A * B * C...* N number of records.

Using NHibernate Linq, the queries looked something like this:

var result =
    Session.Query<MyEntity>()
        .Where(x => x.Id == 1)
        .Fetch(x => x.ChildList1)
        .Fetch(x => x.ChildList2)
        .Single();

After digging around for a while, I found that I could get around this by using NHibernates .ToFuture() method as such:

Session.Query<MyEntity>()
    .Where(x => x.Id == 1)
    .Fetch(x => x.ChildList1)
    .ToFuture();

var result =
    Session.Query<MyEntity>()
        .Where(x => x.Id == 1)
        .Fetch(x => x.ChildList2)
        .ToFuture()
        .Single();

This is a nice simple feature to execute multiple queries while only going to the database once and the queries don't necessarily need to be about related data (just in my instance here they are).

However, we're starting to duplicate logic from the query point of view. We're creating multiple IQueryable<MyEntity> items and filtering both on the identifier. If we take the IQueryable to a variable and create the futures from that, we can save whatever complex logic we may have built up to filter our data such as this:

var query = Session.Query<MyEntity>().Where(x => x.Id == 1);

query.Fetch(x => x.ChildList1).ToFuture();

var result =
    query
        .Fetch(x => x.ChildList2)
        .ToFuture()
        .Single();

Tags:

C# | NHibernate