Avoid N+1 Select with list of NHibernate entities

◇◆丶佛笑我妖孽 提交于 2020-01-15 05:51:06

问题


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();
}

回答1:


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



来源:https://stackoverflow.com/questions/38297825/avoid-n1-select-with-list-of-nhibernate-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!