问题
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