Multiple fetch in ThenFetch
Asked Answered
D

1

6

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 !

Depositor answered 21/10, 2011 at 10:0 Comment(3)
I don't think you can avoid it, unless Fetch(r=>r.FirstAssoc.Another) works, which I doubt.Whim
@Diego thanks, your doubt is confirmed ( expression too complex exception ). But it would be nice to have.Depositor
I have this exact same issue, although my FirstAssoc is a collection so it is FetchMany.ThenFetch.FetchMany.ThenFetch. Would love a solution to this.Leong
N
3

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.

Norrie answered 18/11, 2011 at 3:38 Comment(5)
@Diego - CC you since you may be interested.Norrie
+1, but you are using QueryOver, can we achieve the same with linqtonh ? PS your blog is really interesting:)Depositor
@Felice - Not sure if you can do it with Query<T>, i suspect it isn't possible, but I'll have a play this weekend see how far I can get. Any reason you can't use QueryOver? Thanks for the comment about my blog :) appreciated.Norrie
Well I can eventually resort on using queryover, but I'm just worried about having many API merged together.Depositor
If you're using the repository pattern then those details are hidden away. I primarily use QueryOver but sometimes fall back onto Query, HQL and if required, Native SQL.Norrie

© 2022 - 2024 — McMap. All rights reserved.