Linq To Sql,复杂选择

本文关键字:复杂 选择 Sql To Linq | 更新日期: 2023-09-27 18:17:58

我正在建立一个门户(这是我的爱好项目)和我的索引(主页)页面,我需要写具体的查询。

我想按照指定的顺序获得类别。对于每个类别,我想加载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; }
}

Category可以有很多与它相关的文章。文章可以不分类。

所以我尝试这样做:

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))

这行不通。有什么想法吗?

Linq To Sql,复杂选择

您可以通过像这样使用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
        }

我认为正确的做法是:

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个类别对象和相关文章对象的集合。这可以成为你的显示模型