避免使用NHibernate实体列表进行N + 1选择 [英] Avoid N+1 Select with list of NHibernate entities

查看:93
本文介绍了避免使用NHibernate实体列表进行N + 1选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到由无法修改的代码检索到的NHibernate实体的列表.我想从子实体中为列表中的每个项目选择一个属性,但是它正在为每个项目生成一个新的选择.

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

我正在调用的函数:

public IEnumerable<string> GetTemplateNames(Property property) {
    return property.Rooms.Select(room => room.Template.Name).Distinct();
}

推荐答案

我正在每个集合(以及每个类)上使用 batch-size 设置.在此处查看更多信息:

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

如果是xml映射,请将其添加到您的包中

In case of xml mapping, add this to your bag

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

NHibernate将批量加载所有加载的父项(在上述情况下为Property)的集合...因此,我们得到的不是1 + N,而是1 + N/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实体列表进行N + 1选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆