简体   繁体   中英

Map two Collection of different type using AutoMapper

I have a DTO and an entity both called QuestionnaireSubmission mapper together like this:

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));

My issue is that I can't figure out how to map s.States of type State[] and RespondantAnswers of type IEnumerable<RespondantAnswer>

I have already created a map between these two classes to map them.

 this.CreateMap<State, RespondantAnswer>()
                .ForMember(d => d.QuestionId, d => d.MapFrom(s => s.Subject))
                .ForMember(..)
                .ForMember(..);

However Automapper seems to not be able to do the mapping... What am I missing? Do I reeally have to use the .ConvertUsing() function?

I can't really reproduce the problem, but the following seems to work just as expected. AutoMapper should be able to handle collections with no special setup:

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

See this fiddle for a demonstration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM