How to a NHibernate subquery in Where clause with

2019-09-16 02:40发布

问题:

I'm trying to write a correlated subquery in the where clause like this:

var foo = from d in session.Query<Document>()
          where true == 
              ( from a in session.Query<ACLEntry>()
                where a.Id == d.Id || a.Id == null
                select a.Result
              ).FirstOrDefault()
          select d;

The expected SQL output is very similar to this unanswered question on SO.

I think the Linq statement itself is fine because I can get it to run in LinqPad where I was prototyping. But NHibernate throws me these mysterious errors:

ERROR NHibernate.Hql.Parser [(null)] - NoViableAltException(86@[])

ERROR NHibernate.Hql.Parser [(null)] - MismatchedTreeNodeException(72!=3)

Is this an unsupported scenario with the NHibernate LINQ provider? Any ideas on how I might be able to restructure this query to get around it?

回答1:

Try this instead :

var foo = from d in session.Query<Document>()
          where (from a in session.Query<ACLEntry>()
                  where a.Id == d.Id || a.Id == null
                  select a.Result
                 ).FirstOrDefault() != null
          select d;

Hope this will help !!



回答2:

It is probably having some trouble parsing the true == ... portion of the query.

Might want to try this instead,

var foo = from d in session.Query<Document>()
    where (from a in session.Query<ACLEntry>()
           where a.Id == d.Id || a.Id == null
           select a.Result
          ).FirstOrDefault()
    select d;