将 Dto 与模型绑定,只返回一个 Dto

时间:2021-04-09 18:28:41

标签: c# linq

首先看我的代码:这是ConceptDto

public Guid ConceptId { get; set; }
public string ConceptName { get; set; }
public string ConceptLatinName { get; set; }
public List<ConceptSubDto> ConceptSubSidiary { get; set;}

这是ConceptSubDto

   public Guid ConceptSubId { get; set; }
   public string  ConceptSubName { get; set; }

我有这样的域名。

现在这是我的应用程序层,我想通过 id 获取这些逻辑并只返回一个 ConceptDto,但我不知道必须将这些 dto 与域模型映射:

 public async Task<ConceptManagementDto> GetConceptById(Guid id)
 {
     var concept = await _conceptManagementRepository.Query()
                              .Include(x => x.conceptSubSidiaries)
                              .GetOneAsync(x => x.Id == id);
     return new ConceptManagementDto
            {
                ConceptManagementId = concept.Id,
                ConceptName = concept.ConceptName,
                ConceptLatinName = concept.ConceptLatinName,
                ConceptSubSidiary = ??
            };
}

1 个答案:

答案 0 :(得分:0)

如果您的 DTO 字段较少,此查询应该有效:

public async Task<ConceptManagementDto> GetConceptById(Guid id)
{
     return await _conceptManagementRepository.Query()
        .Where(x => x.Id == id)
        .Select(x = new ConceptManagementDto
        {
            ConceptManagementId = x.Id,
            ConceptName = x.ConceptName,
            ConceptLatinName = x.ConceptLatinName,
            ConceptSubSidiary = x.ConceptSubSidiaries
                .Select(sub => new ConceptSubDto
                {
                    ConceptSubId = sub.ConceptSubId,
                    ConceptSubName = sub.ConceptSubName
                })
                .ToList()
        }).First();
}
相关问题