首页 > 解决方案 > 如何在查询中包含计数属性并在 C# 中重命名结果中的列

问题描述

使用 Entity Framework-core,我需要从我的 ASP.NET 项目中的表中选择属性并获取计数的属性并将其重命名为查询结果。下面是我的查询代码

var result = _context.Subjects.Include(s => s.Course).Include(t => t.Topics);
        return View(await result.ToListAsync());

在我的结果中,我只需要计算每个主题的主题数而不是整个主题列,并且我想将其重命名为结果表的covered_topics。所以,我需要像 t => t.Topics.Count作为no_of_topics

我正在运行 ASP.NET-Core 2.2

请我不知道如何实现。我需要帮助。感谢您期待的指导

标签: c#linqasp.net-coreentity-framework-core

解决方案


您可以Select从查询中创建新的 DTO,如下所示:

public class TopicDTO()
{
    public int NumberOfTopics { get; set; }
}

然后在您的查询中:

var result = _context.Subjects
                     .Include(s => s.Course)
                     .Include(t => t.Topics)
                     .Select(x => new TopicDTO() 
                      {
                          NumberOfTopics = x.Topics.Count()
                      });

return View(await result.ToListAsync());

推荐阅读