我有以下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
答案 0 :(得分:2)
您的映射开始很好,但在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来实现自动化。
答案 1 :(得分:0)
您忘了将 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;
}