NHIbernate(3.1) - Linq group by count by count issue

时间:2011-05-17 10:40:51

标签: linq nhibernate fluent-nhibernate group-by sql-order-by

我正在尝试通过计数来获得一个组,然后按计数工作,但我不断被抛出'Antlr.Runtime.NoViableAltException'。

这是我可以创建的最简单的错误案例。

var results = ArticleStatsRepository.GetAll().GroupBy(x => x.Article.ArticleId)
               .OrderBy(x => x.Count()); 

ArticleStatsRepository.GetAll()返回ArticleStats的IQueryable。

public class ArticleStats
{
    public virtual int ArticleStatsId { get; set; }
    public virtual Article Article { get; set; }
    public virtual User Viewer { get; set; }
    public virtual ArticleStatTypeEN ArticleStatType { get; set; }
    public virtual DateTime DateTime { get; set; }
}

最终我想要执行以下查询。

return ArticleStatsRepository.GetAll()
                  .Where(x => x.DateTime > DateTime.Now.Add(-timeSpan))
                  .Where(x => x.ArticleStatType == ArticleStatTypeEN.View)
                  .GroupBy(x => x.Article.ArticleId)
                  .Select(x => new { ArticleId = x.Key, Count = x.Count() })
                  .OrderByDescending(x => x.Count)
                  .Join(ArticleRepository.GetAll(), artStats => artStats.ArticleId, articles => articles.ArticleId, (artStats, articles) => new MostPopularArticleResult { ArticleId = artStats.ArticleId, ArticleTitle = articles.Content.Title, Count = artStats.Count });

我正在使用Fluent NHibernate 1.2.0.712,它引用了NHibernate:3.1.0.4000。

非常感谢任何帮助!

此致

史蒂夫

更新:这就是我解决问题的方法。不完美,因为我不想开始在其QueryOver中使用HQL,并且希望始终坚持使用IQueryable。

    public virtual IQueryable<MostPopularArticleResult> GetMostPopularArticleResults(TimeSpan timeSpan, IQueryable<Article> filteredArticles, List<ArticleStatTypeEN> types, int take)
    {
        var results = ArticleStatsRepository.GetAllQueryOver().Where(x => x.DateTime > DateTime.Now.Add(-timeSpan));

        results = results.Where(x => x.ArticleStatType.IsIn(types));

        var articleIdsWithCounts = results.Select(
                    Projections.Group<ArticleStats>(x => x.Article.ArticleId),
                    Projections.Count<ArticleStats>(x => x.Article.ArticleId))
                    .OrderBy(Projections.Count<ArticleStats>(x => x.Article.ArticleId))
                    .Desc
                    .Take(take)
                    .List<object[]>()
                    .Select(x => new { ArticleId = (int)x[0], Count = (int)x[1] });

        return articleIdsWithCounts.Join(filteredArticles, artStats => artStats.ArticleId, articles => articles.ArticleId, (artStats, articles) => new MostPopularArticleResult { ArticleId = artStats.ArticleId, ArticleTitle = articles.Content.Title, Count = artStats.Count })
            .AsQueryable();
    }

1 个答案:

答案 0 :(得分:1)