Complex nHibernate QueryOver expression

岁酱吖の 提交于 2019-12-10 01:47:56

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/5519282/complex-nhibernate-queryover-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!