转换为DTO列表属性

本文关键字:属性 列表 DTO 转换 | 更新日期: 2023-09-27 18:13:25

我有以下DTO:

public class QuestionGroupDTO : IBaseDTO
{
    public string Description { get; set; }
    public string Header { get; set; }
    public Guid Id { get; set; }
    public int Order { get; set; }
    public IEnumerable<Services.Forms.Models.RelationForm_QuestionGroupDTO> RelationForms_QuestionGroups { get; set; }
    public IEnumerable<RelationQuestionGroup_QuestionDTO> RelationQuestionGroups_Questions { get; set; }
}

我在转换时遇到RelationQuestionGroups_Questions的问题。

这是我的RelationQuestionGroup_QuestionDTO看起来像

public class RelationQuestionGroup_QuestionDTO
{
    public int Order { get; set; }
    [Required]
    public Guid QuestionGroupId { get; set; }
    [Required]
    public Guid QuestionId { get; set; }
    public virtual QuestionGroupDTO QuestionGroup { get; set; }
    public virtual QuestionDTO Question { get; set; }
}

下面是我如何转换的:

public static QuestionGroupDTO ToDTO(this QuestionGroup src)
{
    var dto = new QuestionGroupDTO
    {
        Id = src.Id,
        Header = src.Header,
        Description = src.Description,
        RelationQuestionGroups_Questions = src.RelationQuestionGroups_Questions.ToList()
    };
    return dto;
}

正如你所看到的,我正试图赋值它并列出它,但是我在这里得到了一个类型转换错误。我不知道该怎么做。

我得到以下错误:

不能隐式地将类型泛型列表转换为System.Collections.Generic.IEnumerble

转换为DTO列表属性

您在映射方面有一个很好的开始,但是在RelationQuestionGroups_Questions = src.RelationQuestionGroups_Questions.ToList(),您试图将List<Entity>分配给List<Dto>。你不能那样做。

您还需要映射任何非基本属性。你可以这样做:

public static QuestionGroupDTO ToDTO(this QuestionGroup src)
{
    var dto = new QuestionGroupDTO
    {
        // ...
        RelationQuestionGroups_Questions = src.RelationQuestionGroups_Questions
                                              .Select(ToDTO)
                                              .ToList()
    };
    return dto;
}

然后添加一个方法将RelationQuestionGroups_Question映射到RelationQuestionGroups_QuestionDTO:

public RelationQuestionGroups_QuestionDTO ToDTO(RelationQuestionGroups_Question entity)
{
    return new RelationQuestionGroups_QuestionDTO
    {
        Order = entity.Order,
        // ...
    };
}

然后你会去看AutoMapper来自动执行这个

您忘记将RelationQuestionGroups_Questions映射到RelationQuestionGroup_QuestionDTO

public static QuestionGroupDTO ToDTO(this QuestionGroup src)
{
    var dto = new QuestionGroupDTO
    {
        Id = src.Id,
        Header = src.Header,
        Description = src.Description,
        RelationQuestionGroups_Questions = src.RelationQuestionGroups_Questions.Select(rq => new RelationQuestionGroup_QuestionDTO
            {
                Order = rq.Order,
                QuestionGroupId = rq.QuestionGroupId,
                QuestionId = rq.QuestionId
            }).ToList()
        };
    return dto;
}