【问题标题】:Merging Multiple related Queries in .Net Core在 .Net Core 中合并多个相关查询
【发布时间】:2020-04-14 00:54:16
【问题描述】:

我想实现一个页面,其中每个类别都有其相关文章,我已实现如下:

  ArticlesHomeViewModel articles  = new ArticlesHomeViewModel
  { 
    category1 = db.Articles.Include(o => o.Category).Where(m => m.category == "Category One Name").limit(4),
    category2 = db.Articles.Include(o => o.Category).Where(m => m.category == "Category two Name").limit(4),
    category3 = db.Articles.Include(o => o.Category).Where(m => m.category == "Category Three Name").limit(4),
    category4 = db.Articles.Include(o => o.Category).Where(m => m.category == "Category Four Name").limit(4),
  }

我想将它们合并到一个查询中,以便能够在视图中对它们进行循环,因为我不知道系统中有多少类别。

【问题讨论】:

标签: c# asp.net-mvc asp.net-core entity-framework-core


【解决方案1】:

定义一个类别数组。

var categories = new[]{"Category One Name","Category Two Name",
                       "Category Three Name","Category Four Name"};

然后

// Include is redundant
var result = db.Articles.Where(art=> categories.Contains(art.Category.Name)) 
            .GroupBy(art=>art.CateGory.Name) // use group for feature uses
            .SelectMany(grouped=>// use selectmany to select individual items
                grouped.OrderBy(t=>t.Id).Take(4))  // and apply paging in group
            .ToArray();  

【讨论】:

    猜你喜欢
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多