简体   繁体   English

Entity Framework Core:只查询相关实体的几个属性

[英]Entity Framework Core: Query only a few properties of related entity

I have related entities Teams and Playlists , where a Team can hold multiple Playlists .我有相关的实体TeamsPlaylists ,其中一个Team可以拥有多个Playlists Now, from a given team, I need all the playlists, but only the Id and PlaylistName properties.现在,对于给定的团队,我需要所有播放列表,但只需要IdPlaylistName属性。

I tried this, but it returns Anonymous Types within the list, that is hard to map to my PlaylistDTO.我试过这个,但它返回列表中的匿名类型,这很难映射到我的 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 is of type List<'a> , 'a is a new { IEnumerable<Int> Id, IEnumerable<string> PlaylistName } dataList<'a> , 'a is a new { IEnumerable<Int> Id, IEnumerable<string> PlaylistName }类型List<'a> , 'a is a new { IEnumerable<Int> Id, IEnumerable<string> PlaylistName }

The statement below works, but is not what I want, since it gets me all the properties from the Playlist entity.下面的语句有效,但不是我想要的,因为它从播放列表实体中获取了所有属性。

Team team = await _context.Teams
    .AsNoTracking()
    .Include(t => t.Playlists)
    .Where(t => t.Id == teamId)
    .FirstOrDefaultAsync();

My two entities:我的两个实体:
Team团队

public class Team
{
   public int Id {get; set; }
   public string TeamName { get; set; }
   //... more properties
   public ICollection<Playlist> Playlists { get; set; }
}

Playlist播放列表

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; }
}

How can I get only the desired properties of the related entity, without being returned an Anonymous Type?如何仅获取相关实体的所需属性,而不返回匿名类型?

Thanks for the help!谢谢您的帮助!

You should not mix the classes from your domain and the responses that your system gives.您不应将域中的类与系统提供的响应混合在一起。

I would create a new class to represent this DTO (Data Transfer Object)我将创建一个新类来表示这个 DTO(数据传输对象)

public class ResponseDTO
{
   public int Id { get; set; }
   public ICollection<Playlist> Playlists { get; set; }
}

In your query use this new class instead of the anonymous object在您的查询中使用这个新类而不是匿名对象

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();

Take a look in the concept of Domain Driven Design to understand the importance of leaving the classes that compose your domain only responsible for that.查看域驱动设计的概念,了解让组成域的类只负责它的重要性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM