c# - 如何在查询中包含计数属性并在 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
请我不知道如何实现。我需要帮助。感谢您期待的指导
解决方案
您可以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());
推荐阅读
- python - Spotify:有人知道 Windows 10 Spotify 桌面应用程序的任何命令提示符命令吗?
- python - Python,函数没有被随机调用
- java - 为什么imageView不显示从字节数组转换为图像的图像
- python - 通过套接字从 Python 向 Particle Photon 发送字节时是否需要校验和?
- javascript - requestAnimationFrame 是如何工作的?
- python - 如何从数据库中填充 3 张幻灯片轮播,其中包含许多页面和未定义的数据量
- javascript - .then 承诺不在反应应用程序中的 axios 删除请求中工作
- ios - iOS adhoc Enterprise Signed App 在某些设备上立即崩溃
- sql - 无法使用 liquibase 添加 NOT NULL 约束
- java - 来自多个线程的不安全访问以将单个值设置为单个变量