2009-12-31 45 views
0

我想通过创建一个简单的博客应用程序来学习MVC和nHibernate。在同一查询中使用Linq选择Nhibernate中的子项和子项数

我有一个帖子表和一个评论表。每篇文章可以有多个评论。现在我认为我必须显示帖子的详细信息和评论数量。

我尝试下面的代码

(from post in DbContext.Posts 
where post.ScheduledDate <= DateTime.Now && post.Approved == true 
orderby post.ScheduledDate descending 
select new { Post = post, CommentCount = post.Comments.Count() }).Take(10); 

这将返回下面的SQL:

SELECT top 10 count(comments1_.Id) as y0_ 
FROM Posts this_ 
left outer join Comments comments1_ 
     on this_.Id=comments1_.PostId 
WHERE (this_.ScheduledDate <= '2009-12-29' and this_.Approved = 1) 
ORDER BY this_.ScheduledDate desc 

很显然抛出一个SQL异常group by不被使用。

+0

您使用的是哪个版本的NHibernate Linq提供程序?在trunk或NHContrib中的最新版本单独的DLL一个? – 2010-01-01 12:51:01

+0

我正在使用使用标准api的那个。 NHContrib之一..使用干线中的那个安全吗?像是有足够的文件为新手? – madaboutcode 2010-01-01 17:22:37

回答

0

看起来这是NHContrib LINQ provider的一些奇怪问题。我升级到nHibernate的第3版,并且新的LINQ提供程序对于相同的查询似乎工作得非常好。

0

这生成的SQL看起来有线,我已经翻译成lambda风格。 试试吧。如果你没有LinqPad去抓住它,检查出来会让你的生活变得很轻松。

DbContext.Posts 
    .Where(p=>p.ScheduledDate<=DateTime.Now && p.Approved) 
    .OrderByDescending(p=>p.ScheduledDate) 
    .Select(p=> new{ post= p,CommentCount = p.Comments.Count()}) 
    .Take(10);