Eager loading child and child-of-child collections in NHibernate

女生的网名这么多〃 提交于 2020-01-01 12:48:46

问题


I've got a problem with NHibernate trying to load a small hierarchy of data. My domain model looks like:

class GrandParent
{
    int ID{get;set;}
    IList<Parent> Parents {get; set;}
}

class Parent
{
    IList<Child> Children {get; set;}
}

class Child
{
}

and I would like to eager load all parents and children for a given GrandParent. This Linq-to-NH query creates the correct SQL and loads the GrandParent as expected: (the example assumes the grandparent has 2 parents who each have 2 child objects - so 4 child objects in total).

var linq = session.Linq<GrandParent>();
linq.Expand("Parents");
linq.Expand("Parents.Children");
linq.QueryOptions.RegisterCustomAction(c => 
    c.SetResultTransformer(new DistinctRootEntityResultTransformer()));
var grandparent = (select g from session.Linq<GrandParent>()
                   where g.ID == 1
                   select g).ToList();

Assert(grandparent.Count == 1); //Works
Assert(grandparent.Parents.Count == 2); //Fails - count = 4!

The grandparent.Parents collection contains 4 items, 2 of which are duplicates. It seems the DistinctRootEntityResultTransformer only works on collections 1 level deep, so the Parents collection is duplicated depending on how many Child objects each parent has.

Is it possible to get NH to only include the distinct Parent objects?

Thanks very much.


回答1:


If your mapping is set to FetchType.Join, try changing it to FetchType.Select.



来源:https://stackoverflow.com/questions/1362794/eager-loading-child-and-child-of-child-collections-in-nhibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!