Complex nHibernate QueryOver expression
Asked Answered
D

1

11

I have the following objects in a hierarchy A > B > C > D. Each object is mapped to a table. I'm trying to write the following SQL using QueryOver:

SELECT B
FROM A, B, C, D
WHERE A.ID = B.ID
  AND B.ID = C.ID
  AND C.ID = D.ID
WHERE A.NUMBER = 'VALUE'
  AND D.NAME IN ('VALUE1', 'VALUE2')

I have the C# code so far:

string[] entityNames = entityAttributes.Select(e => e.Name).ToArray();
string customerNumber = 2;

return session.QueryOver<B>()
              .JoinQueryOver(b => b.C)
              .JoinQueryOver(c => c.D)
              .WhereRestrictionOn(d => d.Name).IsIn(entityNames)
              .List<B>();

What's missing here is the A > B link. I cannot figure out how to add the join to A restricting it on the NUMBER field. I tried the following but the .JoinQueryOver(b => b.C) is looking for type A instead of finding type B.

return session.QueryOver<B>()
                .JoinQueryOver(b => b.A)
                    .Where(a => a.Number == customerNumber)
              .JoinQueryOver(b => b.C) **//Looks for type A instead of B**
              .JoinQueryOver(c => c.D)
              .WhereRestrictionOn(d => d.Name).IsIn(entityNames)
              .List<B>();

How can I add type A to this query while still returning type B?

Daryl answered 1/4, 2011 at 21:55 Comment(0)
S
13

you can use Aliases to join your table like

B tB = null;
A tA = null;
C tC = null;
D tD = null;
var qOver = HibSession.QueryOver<B>(() => tB)
.JoinAlias(() => tB.A, () => tA, JoinType.LeftOuterJoin)
.Where(() => tA.Number == customerNumber)
.JoinAlias(() => tB.C, () => tC, JoinType.LeftOuterJoin)
.JoinAlias(() => tC.D, () => tD, JoinType.LeftOuterJoin)
.Where(Restrictions.On(() => tD.Name).IsIn(entityNames))
.List<B>();

I hope it's helpful.

Sophistic answered 1/4, 2011 at 23:4 Comment(1)
Thank you! This has worked like a charm in multiple scenarios of my application!Daryl

© 2022 - 2024 — McMap. All rights reserved.