简体   繁体   中英

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 . Now, from a given team, I need all the playlists, but only the Id and PlaylistName properties.

I tried this, but it returns Anonymous Types within the list, that is hard to map to my 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 }

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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