Unwanted tree / hierarchy loading with Nhibernate

This is not a question as such, I studied this issue over the past few days and thought that I would like to contribute to what attracted a lot of scattered ideas that I read and put forward a solution to the problem ...

The problem is loading n level children in Nhibernate, and that nHibernate will not know the depth of the tree. I saw how this was solved using direct sql and Union All, but unfortunately I could not get this to work, as a rule, because nhibernate did not know that you were looking to load objects. So I looked at the following code to load an object using criteria

        var children = Session.CreateCriteria<MenuNode>()
            .SetFetchMode("Children", FetchMode.Eager)
            .Add(Expression.Eq("Id", 1))
            .List<MenuNode>();

This will load the child for Id 1, from here you can use the In operator to quickly load multiple objects at once. Therefore, I just need to find all the node id belonging to this hierarchy and load them using the In statement.

So, if I create a parent table for the hierarchy and each node has a hierarchy identifier, then I can get a list of all node id for this hierarchy using this hql

var sql = "select Distinct id from Nodes where (HierarchyId = :id) ";
var ids = Session.CreateSQLQuery(sql)
          .SetInt32("id", id)
          .List();

and from here download all children only for this tree using

var children = Session.CreateCriteria<MenuNode>()
            .SetFetchMode("Children", FetchMode.Eager)
            .Add(Expression.In("Id", ids))
            .List<MenuNode>();

The only problem is that you did not want to load first level levels from the parent hierarchy table, which can be done fine.

var menu = Session.CreateCriteria<Menu>()
            .SetFetchMode("RootNodes", FetchMode.Eager)
            .Add(Expression.Eq("Id", id))
            .List<Menu>();

, SQL n . , . , , .

MultiCriteria .

http://nhforge.org/blogs/nhibernate/archive/2008/09/06/eager-loading-aggregate-with-many-child-collections.aspx

, -.

+5
1

, , , , . . http://ayende.com/Blog/archive/2009/08/28/nhibernate-tips-amp-tricks-efficiently-selecting-a-tree.aspx

return session.CreateCriteria<MenuNode>()
    .SetFetchMode("Children", FetchMode.Join)
    .SetResultTransformer(new DistinctRootEntityResultTransformer())
    .List<MenuNode>();

, , , , .

+2

All Articles