Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple fetch in ThenFetch

I've an associated entity with <many-to-one> and that entity has two <many-to-one> that I want to fetch at once. I can achieve this by this query:

 var tshead = session.Query<MainEntity>()
                .Fetch(r=>r.FirstAssoc).ThenFetch(p=>p.Other)
                .Fetch(r=>r.FirstAssoc).ThenFetch(p=>p.Another)
                .Take(10)
                .ToList();

As you can see I had to wrote twice .Fetch(r=>r.FirstAssoc) I'm sure I can avoid this but I cant figure out how. Any idea ?

Thanks !

like image 808
Felice Pollano Avatar asked Oct 21 '11 10:10

Felice Pollano


1 Answers

If you select a specific 'MainEntity' then you can do it using QueryOver like so:

 FirstAssoc firstAssoc = null;
 Other other = null;
 Another another = null;

 tshead = session.QueryOver<MainEntity>()
               .Where(x => x.Id == id)
               .JoinAlias(x => x.FirstAssoc, () => firstAssoc)
               .JoinAlias(() => firstAssoc.Other, () => other)
               .JoinAlias(() => firstAssoc.Another, () => another)
               .SingleOrDefault();

I've written about it here:

http://www.philliphaydon.com/2011/04/nhibernate-querying-relationships-are-depth/

You can't do:

One-Many-Many

only One-Many-One.

I'm not sure you can do Many-Many-One, transforming that would be too difficult.

like image 142
Phill Avatar answered Dec 12 '22 03:12

Phill