[英]AutoMapper - Map collections of different types to collection of another type with nesting
[英]Map two Collection of different type using AutoMapper
我有一个 DTO 和一个实体,它们都称为QuestionnaireSubmission
映射器,如下所示:
public QuestionSubmissionMapper() => this.CreateMap<DTO.QuestionnaireSubmission, QuestionnaireSubmission>()
.ForMember(d => d.ParticipantId, d => d.MapFrom(s => s.ParticipationId))
.ForMember(d => d.SurveyVersionId, d => d.MapFrom(s => s.Survey.Version))
.ForMember(d => d.RespondantAnswers, d => d.MapFrom(s => s.States));
我的问题是我无法弄清楚如何 map s.States of type State[]
和RespondantAnswers of type IEnumerable<RespondantAnswer>
我已经在这两个类之间创建了一个 map 到 map 。
this.CreateMap<State, RespondantAnswer>()
.ForMember(d => d.QuestionId, d => d.MapFrom(s => s.Subject))
.ForMember(..)
.ForMember(..);
但是 Automapper 似乎无法进行映射......我错过了什么? 我真的必须使用.ConvertUsing()
function 吗?
我无法真正重现该问题,但以下似乎按预期工作。 AutoMapper 无需特殊设置即可处理 collections:
var mapper = new MapperConfiguration(cfg => {
cfg.CreateMap<SourceQuestionnaireSubmission, DestQuestionnaireSubmission>()
.ForMember(d => d.ParticipantId, d => d.MapFrom(s => s.ParticipationId))
.ForMember(d => d.SurveyVersionId, d => d.MapFrom(s => s.Survey.Version))
.ForMember(d => d.RespondantAnswers, d => d.MapFrom(s => s.States));
cfg.CreateMap<State, RespondantAnswer>()
.ForMember(d => d.QuestionId, d => d.MapFrom(s => s.QuestionId));
})
.CreateMapper();
var source = new SourceQuestionnaireSubmission
{
ParticipationId = 1,
Survey = new Survey { Version = 10 },
States = new []
{
new State { QuestionId = 100 },
new State { QuestionId = 999 }
}
};
var dest = mapper.Map<SourceQuestionnaireSubmission, DestQuestionnaireSubmission>(source);
Console.WriteLine("ParticipantId: {0}", dest.ParticipantId);
Console.WriteLine("SurveyVersionId: {0}", dest.SurveyVersionId);
Console.WriteLine("RespondantAnswers: {0}",
string.Join(", ", dest.RespondantAnswers.Select(a => a.QuestionId)));
// Output:
// ParticipantId: 1
// SurveyVersionId: 10
// RespondantAnswers: 100, 999
请参阅this fiddle进行演示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.