Monday, December 19, 2016

NHibernate.Hql.Ast.ANTLR.QuerySyntaxException

Last week a colleagued shared the following error message:

NHibernate.Hql.Ast.ANTLR.QuerySyntaxException: Exception of type 'Antlr.Runtime.NoViableAltException' was thrown.

The error happened in an ASP.NET Web API controller using the built-in OData functionality in combination with NHibernate. Further investigation showed that the problem occured when one of the following OData filters were used:

  • startswith
  • a combination of ‘and’ and/or ‘or’ conditions

Some query url examples that are causing trouble:

  • Products?$filter=startswith(ProductName,’ABC’)
  • Orders?$filter=year(OrderData eq 2016 and OrderType eq 'FastShipping'

NHibernate is unable to parse the expression tree generated by ASP.NET Web API. Luckily someone already created a solution for this problem; https://github.com/Pathoschild/webapi.nhibernate-odata/blob/master/README.md

Install the NuGet package and apply the attribute to your queryable Web API controller action:

[Queryable, FixOdataQuery]
public IQueryable<Product> Get()
{
    return ...;
}

No comments: