Linq To Sql,复杂选择

时间:2011-12-16 10:09:01

标签: c# linq entity-framework linq-to-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 个答案:

答案 0 :(得分: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
        }

答案 1 :(得分: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))
});

结果将是匿名对象的集合。每个对象将具有1个Category对象和相关Articles对象的集合。这可以成为您的显示模型。