2011-12-16 99 views
1

我正在建立一個門戶網站(這是我的愛好項目),併爲我的索引(家)頁我需要寫具體的查詢。Linq到SQL,複雜的選擇

我想按指定順序獲取類別。對於每個類別,我想加載N個最近附加的文章。所以基本上我的主頁將看起來像

Category 1   Category 2 
Article title 1  Article title 1 
Article title 2  Article title 2 
....     .... 
Article title N  Article title N 


Category 3   Category 4 
Article title 1  Article title 1 
Article title 2  Article title 2 
....     .... 
Article title N  Article title N 

我簡化領域模型是這樣的:

public class CategoryInfo 
{ 
    public virtual Int64 ParentId? { get; set; } 

    public virtual String Name { get; set; } 

    public virtual Int32 DisplayOrder { get; set; } 

    public virtual ICollection<ArticleInfo> Articles { get; set; } 
} 

public class ArticleInfo 
{ 
    public virtual String Title { get; set; } 

    public virtual DateTime Published { get; set; } 

    public virtual Int64? CategoryId { get; set; } 

    public virtual CategoryInfo { get; set; } 
} 

類別可以有與之相關的許多文章。文章可以未分類。

所以我試圖做這種方式:

var query = _categoryService.GetCategories().Where(x => !x.ParentId.HasValue) // Getting only top level categories 
              .OrderBy(x => x.DisplayOrder)  // Sorting 
              .Select(x => x.Articles.OrderByDesc(a => a.Published).Take(N)) 

這是行不通的。有任何想法嗎 ?

回答

2

可以使用的SelectMany這樣做:

categories.Where(x => !x.ParentId.HasValue) // Getting only top level categories 
      .OrderBy(x => x.DisplayOrder) // Sorting 
      .SelectMany(x => x.Articles.OrderByDescending(a => a.Published).Take(10)) 
      .GroupBy(x => x.Category); 

你可以遍歷它是這樣的:

 foreach (var group in query) 
     { 
      Console.Write(group.Key); //the category 
      //group is an enumerable of articles 
     } 
+0

GroupBy運營商的目的是什麼? – Auk 2011-12-16 11:38:32

0

我認爲,正確的做法是:

var query = _categoryService.GetCategories().Where(x => !x.ParentId.HasValue) // Getting only top level categories 
              .OrderBy(x => x.DisplayOrder)  // Sorting 
              .Select(x => new { 
Category = x, 
Articles = x.Articles.OrderByDesc(a => a.Published).Take(N)) 
}); 

結果將是匿名對象的集合。每個對象都有一個Category對象和一個相關的Articles對象集合。這可以成爲您的顯示模型。