【问题标题】:How to include counted property in a query and rename the column in the result in c#如何在查询中包含计数属性并在 C# 中重命名结果中的列
【发布时间】:2019-04-25 15:41:59
【问题描述】:

使用 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# linq asp.net-core entity-framework-core


【解决方案1】:

您可以从查询中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());

【讨论】:

  • 非常感谢您提供本指南。它让我看到了正确的方向。但是,您能否解释一下为此使用 viewModel 是否是一个好主意,因为它旨在用于在网格列表视图页面中呈现。另外,是否还需要 .Include(s => s.Course) 和 .Include(t=>t.topics)?
  • @Josh 使用 viewModel 将是个人偏好。这两个.Include() 语句可能不是必需的,但我需要查看CourseTopic 的类是什么样的,以及Subjects 上下文。使用.Include() 语句将提高更大数据集的性能。
  • Includes 是多余的 - 投影查询属于 Ignored Includes 类别。
猜你喜欢
  • 2017-12-11
  • 1970-01-01
  • 2020-11-14
  • 1970-01-01
  • 1970-01-01
  • 2020-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多