Eagerly load recursive relation

前端 未结 3 1555
囚心锁ツ
囚心锁ツ 2020-12-31 19:43

I have a recursive one-to-many relationship that has the default lazy value of true. What code can I write against the NH API that will efficiently retrieve the ENTIRE tree

3条回答
  •  太阳男子
    2020-12-31 20:20

    See Ayende's site: Efficiently Selecting a Tree. I have successfully used this technique in my own applications. With ICriteria, it looks like this:

    session.CreateCriteria()
        .SetFetchMode("SubCategories", FetchMode.Join)
        .SetResultTransformer(new DistinctRootEntityResultTransformer())
        .List()
        .Where(x => x.ParentCategory == null);
    

    The main difference between this version and what you tried is how the "ParentCategory == null" filter is applied. It has to be left out of the query that is sent to the database in order to retrieve the whole tree - but we still need the query to only return the root nodes of the tree, so we'll use linq to find those after the database query has completed.

提交回复
热议问题