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 !

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115

1 Answers1

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.

Phill
  • 18,398
  • 7
  • 62
  • 102
  • @Diego - CC you since you may be interested. – Phill Nov 18 '11 at 03:39
  • +1, but you are using QueryOver, can we achieve the same with linqtonh ? PS your blog is really interesting:) – Felice Pollano Nov 18 '11 at 07:45
  • @Felice - Not sure if you can do it with Query, 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. – Phill Nov 18 '11 at 15:05
  • Well I can eventually resort on using queryover, but I'm just worried about having many API merged together. – Felice Pollano Nov 18 '11 at 15:40
  • 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. – Phill Nov 19 '11 at 01:24