views:

344

answers:

2

I have a problem trying to load a tree, this is my case, I have an entity associated with itself (Hierarchic) with n levels; the question is, Can I load eagerly the entire tree using ICriteria or HQL?

Thanks in advance for any help. Ariel

+1  A: 

Yes... just set correct fetchmode.


i'll include example in a minute.


Example taken from here =>

IList cats = sess.CreateCriteria(typeof(Cat))
    .Add( Expression.Like("Name", "Fritz%") )
    .SetFetchMode("Mate", FetchMode.Eager)
    .SetFetchMode("Kittens", FetchMode.Eager)
    .List();

You can specify to eager load child of child too =>

.SetFetchMode("Kittens.BornOn", FetchMode.Eager)

In case you are using Linq to NHibernate, use Expand method =>

var feedItemQuery = from ad in session.Linq<FeedItem>().Expand("Ads")
                           where ad.Id == Id
                           select ad;

And i would recommend to use helper method that creates string from passed in lambda expression.


Quite likely that it's possible to tell Criteria to load whole tree. But i'm not aware about that and i prefer specifying what exactly i need (seems dangerous to load everything).


Does this helps?

Arnis L.
I know I can load collections related to an entity using FetchMode, but I want to load the entire tree, not only the next level.Using your approach I would do: .SetFetchMode("Children", FetchMode.Join) .SetFetchMode("Children.Children", FetchMode.Join) .SetFetchMode("Children.Children.Children", FetchMode.Join) etc
Argons
+3  A: 

This article contains a solution for fetching the entire tree using NHibernate. See the sub-heading "Eager load ancestors and descendants". The author uses a hierarchical query in SQL Server 2005.

Jamie Ide
Thanks for the help
Argons