使用:正確生成NHibernate的OrderByDescending拋出異常`識別錯誤occurred`
.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)
如何解決這個問題,或者替代有什麼建議?
謝謝!
更新
更新的排序依據實際包含null檢查。
在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
你在orderBy中放置了一個布爾條件,shouldnt布爾條件在where子句和orderBy應該在你想要命令的屬性上?順序應該只是'.OrderByDescending(review => review.Country.Id)'將其他檢查移動到where子句的位置 – harishr
@entre:我不需要按條件過濾,我只需要按條件爲真。 –