[英]Entity Framework Core: Query only a few properties of related entity
我有相关的实体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 }
类型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(数据传输对象)
public class ResponseDTO
{
public int Id { get; set; }
public ICollection<Playlist> Playlists { get; set; }
}
在您的查询中使用这个新类而不是匿名对象
var data = await (from team in _context.Teams
where team.Id == teamId
select new ResponseDTO
{
Id = team.Playlists.Select(pl => pl.Id),
PlayListName = team.Playlists.Select(pl => pl.PlayListName)
}).ToListAsync();
查看域驱动设计的概念,了解让组成域的类只负责它的重要性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.