问题
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