[英]Avoid N+1 Select with list of NHibernate entities
I receive a list of NHibernate entities that were retrieved by code that I cannot modify. 我收到由无法修改的代码检索到的NHibernate实体的列表。 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();
}
I am using a batch-size
setting on each collection (and each class as well) . 我在每个集合(以及每个类)上使用
batch-size
设置。 Check more here: 在这里检查更多:
In case of xml mapping, add this to your bag 如果是xml映射,请将其添加到您的包中
<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 NHibernate将批量加载所有加载的父项(在上述情况下为
Property
)的集合...因此,我们将得到1 + N / 50而不是1 + N
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.