Avoid N+1 Select with list of NHibernate entities
Asked Answered
P

1

2

I receive a list of NHibernate entities that were retrieved by code that I cannot modify. I want to select a property from a child entity for each item in the list, but it is generating a new select for each item.

How can I get the sub-resources without changing the query that generated the entities passed in or changing the mapping (both of which would have an impact on unrelated code). Ideally, I wouldn't have to create a custom query at this layer of my code either.

Here is a sample. My entities:

public class Property {
    public IList<Room> Rooms { get; set; }
}
public class Room {
    public Template Template { get; set; }
}
public class Template {
    public string Name { get; set; }
}

And the function I am calling:

public IEnumerable<string> GetTemplateNames(Property property) {
    return property.Rooms.Select(room => room.Template.Name).Distinct();
}
Petitioner answered 11/7, 2016 at 1:0 Comment(0)
K
3

I am using a batch-size setting on each collection (and each class as well). Check more here:

NHibernate Criteria with Distinct Parent Load All Children?

In case of xml mapping, add this to your bag

<bag name="Rooms" ... batch-size="50">

NHibernate will be loading collections for all loaded parent items (Property in the above case) in batches... So instead of 1 + N, we will get 1 + N / 50

Kutchins answered 11/7, 2016 at 5:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.