【问题标题】:Entity Framework Core: Query only a few properties of related entityEntity Framework Core:只查询相关实体的几个属性
【发布时间】:2021-11-01 13:14:52
【问题描述】:

我有相关实体TeamsPlaylists,其中Team 可以容纳多个Playlists。现在,我需要来自给定团队的所有播放列表,但只需要 IdPlaylistName 属性。

我试过了,但它在列表中返回匿名类型,这很难映射到我的 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 =&gt; pl.Id), PlayListName = team.Playlists.Select(pl =&gt; pl.PlayListName) }).ToListAsync(); 其中 dataDTO 是您的对象。
  • 创建一个视图模型。加载您的播放列表并使用 automapper 将播放列表中的属性映射到您的视图模型,然后移交您的视图模型。完成。

标签: c# linq entity-framework-core asp.net-core-mvc


【解决方案1】:

您不应将域中的类与系统给出的响应混为一谈。

我会创建一个新类来表示这个 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();

查看Domain Driven Design 的概念,了解让组成您的域的类只负责这一点的重要性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 2020-01-13
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    相关资源
    最近更新 更多