Making nhibernate do a join on a many-to-many relationship
-
28-10-2019 - |
문제
I have the following situation I am am stuck. I have an entity called ContactAssociation which has(among others) the properties Client and a Contact. I have to get all the Contacts for a Client that fulfill some condintions. The conditions are: Each Client has property BusinessEntities which is a collection of BusinessEntity, each BusinessEntity has a BusinessLevel. This is the code, I am sure will make this more understandable:
link.Session.QueryOver<ContactAssociation>(() => ca)
//.Fetch(asoc => asoc.Client)
.JoinAlias(() => ca.Client, ()=> client)
.Left.JoinQueryOver<BuEntry>(() => client.BuEntries, () => be)
.Where(() => client.ID == clientKey)
.Where(() => be.BuLevel.LevelNo > buLevel);
Ok so I wrote the thing like this and I keep getting an error that the property BuLevel.LevelNo cannot be found But it is there in the model
I tried criteria but I saw the same error only it was in NHProfiler instead of Visual Studio and there was a more cryptic error in Visual Studio. Anyway ... I eventually solved the problem with a sql query but how should I write the QueryOver and/or Criteria to get the proper results?
Thank you in advance
P.S.
Here is my SQL Query:
careTeamMembers = link.Session.CreateSQLQuery(@"select c.* from ContactAssociation ca
inner join Contact c
on ca.contactkey = c.contactkey
left join ContactBu cb
on cb.contactkey = c.contactkey
left join BuEntry be
on cb.entrykey = be.entrykey
left join BuLevel bl
on be.levelkey = bl.levelkey
where ca.clientkey = :clientkey
and bl.levelno > :level")
.AddEntity(typeof(Contact))
.SetInt32("clientkey", clientKey)
.SetInt32("level", buLevel)
.SetMaxResults(1000)
.List<Contact>();
해결책
You're missing a join on BULevel
link.Session.QueryOver<ContactAssociation>(() => ca)
//.Fetch(asoc => asoc.Client)
.JoinAlias(() => ca.Client, ()=> client)
.Left.JoinQueryOver<BuEntry>(() => client.BuEntries, () => be)
.Where(() => client.ID == clientKey)
.JoinQueryOver<BuLevel>(() => be.BuLevel)
.Where(bu => bu.LevelNo > buLevel);