【发布时间】:2021-11-01 13:14:52
【问题描述】:
我有相关实体Teams 和Playlists,其中Team 可以容纳多个Playlists。现在,我需要来自给定团队的所有播放列表,但只需要 Id 和 PlaylistName 属性。
我试过了,但它在列表中返回匿名类型,这很难映射到我的 PlaylistDTO。
var data = await (from team in _context.Teams
where team.Id == teamId //teamId comes from incoming request
select new
{
Id = team.Playlists.Select(pl => pl.Id),
PlayListName = team.Playlists.Select(pl => pl.PlayListName)
}).ToListAsync();
data 的类型为 List<'a> , 'a is a new { IEnumerable<Int> Id, IEnumerable<string> PlaylistName }
下面的语句有效,但不是我想要的,因为它从播放列表实体中获取了所有属性。
Team team = await _context.Teams
.AsNoTracking()
.Include(t => t.Playlists)
.Where(t => t.Id == teamId)
.FirstOrDefaultAsync();
我的两个实体:
团队
public class Team
{
public int Id {get; set; }
public string TeamName { get; set; }
//... more properties
public ICollection<Playlist> Playlists { get; set; }
}
播放列表
public class Playlist
{
public int Id { get; set; }
public string PlaylistName {get; set; }
// .. other properties
public int? TeamId { get; set; }
public virtual Team Team { get; set; }
}
如何只获取相关实体的所需属性,而不返回匿名类型?
感谢您的帮助!
【问题讨论】:
-
有什么问题?而不是投影到匿名对象 - 投影到 DTO。
-
您可以简单地
where team.Id == teamId //teamId comes from incoming request select new dataDTO { Id = team.Playlists.Select(pl => pl.Id), PlayListName = team.Playlists.Select(pl => pl.PlayListName) }).ToListAsync();其中 dataDTO 是您的对象。 -
创建一个视图模型。加载您的播放列表并使用 automapper 将播放列表中的属性映射到您的视图模型,然后移交您的视图模型。完成。
标签: c# linq entity-framework-core asp.net-core-mvc