使用时:
.OrderByDescending(review => review.Country.Id == reviewCountryID)
正确生成SQL查询,不会抛出任何错误。
使用时:
.OrderByDescending(review =>
review.User != null &&
review.User.Country != null &&
review.User.Country.Id == userCountryID
)
正在抛出异常:
NHibernate.Hql.Ast.ANTLR.QuerySyntaxException
A recognition error occurred.
at NHibernate.Hql.Ast.ANTLR.ErrorCounter.ThrowQueryException()
at NHibernate.Hql.Ast.ANTLR.HqlSqlTranslator.Translate()
at NHibernate.Hql.Ast.ANTLR.QueryTranslatorImpl.DoCompile(IDictionary`2 replacements, Boolean shallow, String collectionRole)
at NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory.CreateQueryTranslators(IASTNode ast, String queryIdentifier, String collectionRole, Boolean shallow, IDictionary`2 filters, ISessionFactoryImplementor factory)
at NHibernate.Engine.Query.QueryPlanCache.GetHQLQueryPlan(IQueryExpression queryExpression, Boolean shallow, IDictionary`2 enabledFilters)
at NHibernate.Impl.AbstractSessionImpl.GetHQLQueryPlan(IQueryExpression queryExpression, Boolean shallow)
at NHibernate.Impl.AbstractSessionImpl.CreateQuery(IQueryExpression queryExpression)
at NHibernate.Linq.DefaultQueryProvider.PrepareQuery(Expression expression, ref IQuery query, ref NhLinqExpression nhQuery)
at NHibernate.Linq.DefaultQueryProvider.Execute(Expression expression)
at NHibernate.Linq.DefaultQueryProvider.Execute(Expression expression)
at Remotion.Linq.QueryableBase`1.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList(IEnumerable`1 source)
有关如何解决此问题或替代方案的任何建议吗?
谢谢!
更新
更新了OrderBy以实际包含空检查。
在Select()
中投射表达式review.User != null && review.User.Country != null && review.User.Country.Id == 144
按预期工作,但OrderBy中的相同条件会抛出异常。
更新
下面修复了多个连接的问题,但是在对它们执行布尔条件时却没有这个问题:
使用投影属性执行OrderByDescending,然后仅投影实体查询,例如:
.Select(review => new
{
Review = review,
ReviewUserCountryId = (review.User != null && review.User.Country != null) ? review.User.Country.Id : (int?)null
})
.OrderByDescending(review => ReviewUserCountryId)
.Select(reviewInfo => reviewInfo.Review) // for aliasing assuming that ReviewUserCountryId won't be needed later in the query
// rest of query
答案 0 :(得分:10)
似乎对于多个连接,NHibernate拒绝订购布尔值。
解决方案是对OrderBy中的整数进行排序,例如:
TestButton
如果有更好的解决方案,请添加。