2009-12-31 41 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);