简体   繁体   中英

Complex nHibernate QueryOver expression

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 => bC) 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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM