当起始点是List时,NHibernate将加载具有MultiQuery/ multiccriteria

本文关键字:加载 NHibernate multiccriteria MultiQuery List Entity | 更新日期: 2023-09-27 18:18:37

我看到过类似的问题的答案,你有一个单一的实体,并希望使用多个查询(而不是一个大的连接集)加载其所有的集合:

NHibernate Multiquery for eager loading

我的问题是,当查询的起点是一个实体列表时,如何做类似的事情?

类型:ContainerType, CollectionType1, CollectionType2, CollectionType[3....10]

ContainerType {
    List<CollectionType1> collection;
    List<CollectionType2> collection2;
}
CollectionType1 {
    List<CollectionType1> childCollection;
    List<CollectionType3> childCollection3;
    ...
    List<CollectionType10> childCollection10;
}

我想避免的

List<ContainerType> containers = new Session.Linq<ContainerType>()
    .FetchMany(container => container.collection)
    .ThenFetchMany(collection => collection.childCollection)
    .FetchMany(container => container.collection2)
    .ToList();

是否有一种方法可以使用多查询/多条件来设置这些连接假设我没有一个单一的Id,我可以将它们全部关联到?

我是如何最终使它按预期工作的

Session.Linq<ContainerType>
    .FetchMany(container => container.CollectionType1s)
    .ToList();
Session.Linq<CollectionType1>
    .FetchMany(parent => parent.Children)
    .ToList();
Session.Linq<CollectionType1>
    .FetchMany(allType1s => allType1s.CollectionType3)
    .ThenFetchMany(type3 => type3.CollectionType3_1) // etc.
     // etc.
    .ToList();
// etc.
List<ContainerType> containers = Session.Linq<ContainerType>()
    .ToList();

当起始点是List<Entity>时,NHibernate将加载具有MultiQuery/ multiccriteria

它的工作原理与单个实体完全相同,因为它们都将在缓存中:

session.Linq<ContainerType>()
    .FetchMany(container => container.collection2)
    .ToFuture();
List<ContainerType> containers = session.Linq<ContainerType>()
    .FetchMany(container => container.collection)
    .ThenFetchMany(collection => collection.childCollection)
    .ToList();

唯一的问题是,它将获取所有container两次,这可能是缓慢的,如果他们有很多数据或非常大的文本字段…