使用HQL / Antlr.Runtime.NoViableAltException优化查询

时间:2014-01-07 15:05:28

标签: c# nhibernate hql

我有代码:

if (request.OrderBy != "PricesCount")
                query = query.ApplyOrder(request);
else
   {
       if (request.OrderDirection == "ASC")
          {
            query = query.ToList().OrderBy(p => p.Prices.Count).AsQueryable(); //must be optimize!
          }
       else
          query = query.ToList().OrderByDescending(p => p.Prices.Count).AsQueryable(); //must be optimize!
  } 
 query = query.Page(pageNumber, pageSize);
 var result = query.ToList();

query的类型为NHibernate.Linq.NhQueryable<Book>

我必须删除导致从DB加载所有图书的ToList()

如果我尝试使用某些代码:

query = query.OrderBy(p => p.Prices.Count);
...
var result = query.ToList();//I have Antlr.Runtime.NoViableAltException

Exception of type 'Antlr.Runtime.NoViableAltException' was thrown. [.Take[Book](.Skip[Book](.OrderBy[Book,System.Int32](NHibernate.Linq.NhQueryable`1[Book], Quote((p, ) => (p.Prices.Count)), ), p1, ), p2, )]

1 个答案:

答案 0 :(得分:0)

result = query.Where(p=>p.Price > 5).ToList(); //put whatever filter you want

您不需要像第一段那样.ToList().AsQueryable().ToList()

如果您无法过滤结果,那么您应该实现某种分页:

result = query.Skip(x).Take(y).ToList(); //You will need to send in X and Y based on what page you are on and how many items per page you use

result = query.Where(p=>p.Price>5).OrderBy(p=>p.Prices.Count).ToList()

就像我在评论中所说,如果你没有提供where子句,或者如果你没有提供.Take(y),那么这将返回数据库中的所有项目。如果你.Skip(x).Take(y),你将自己传入X和Y,你需要确定适合你的应用程序的分页。