Difference between revisions of "AutoMapper"
From Logic Wiki
| Line 9: | Line 9: | ||
== Creating Profile == | == Creating Profile == | ||
This is a complex tree model structure | This is a complex tree model structure | ||
| − | + | '''To create parent children mapping, create the child mapping first and then create parent children mapping. ''' | |
CreateMap<Source, Target> | CreateMap<Source, Target> | ||
<pre> | <pre> | ||
Revision as of 10:04, 1 October 2019
Installation
Command line
dotnet add package AutoMapper
PM>
Install-Package AutoMapper
Creating Profile
This is a complex tree model structure To create parent children mapping, create the child mapping first and then create parent children mapping. CreateMap<Source, Target>
public class ApplicationProfile:AutoMapper.Profile
{
public ApplicationProfile()
{
CreateMap<Common.Models.Entities.VDS.Proposal, ProposalForm>();
CreateMap<Common.Models.Entities.VDS.Section, Models.Insurance.Section>();
CreateMap<Common.Models.Entities.VDS.ProposalQuestionAnswer, ProposalFormQuestionAnswer>()
.ForMember(dest => dest.ProposalFormQuestionAnswerPossibleAnswer, opt => opt.MapFrom(src => src.PossibleAnswer));
CreateMap<Common.Models.Entities.VDS.PossibleAnswer, ProposalFormQuestionAnswerPossibleAnswer>();
CreateMap<Common.Models.Entities.VDS.Question, Models.Insurance.Question>()
.ForMember(dest => dest.QuestionType, opt => opt.MapFrom(src => src.QuestionType));
CreateMap<Common.Models.Entities.VDS.QuestionType, Models.Insurance.QuestionType>();
CreateMap<Common.Models.Entities.VDS.ProposalSection, Models.ProposalForm.ProposalFormSection>()
.ForMember(dest => dest.Section, opt => opt.MapFrom(src => src.Section))
.ForMember(dest => dest.Questions, opt => opt.MapFrom(src => src.ProposalQuestion));
CreateMap<Common.Models.Entities.VDS.ProposalQuestion, Models.ProposalForm.ProposalFormQuestion>()
.ForMember(dest => dest.Question, opt => opt.MapFrom(src => src.Question))
.ForMember(dest => dest.QuestionAnswers, opt => opt.MapFrom(src => src.ProposalQuestionAnswer));
CreateMap<Common.Models.Entities.VDS.Proposal, ProposalForm>()
.ForMember(dest => dest.ProposalFormSections, opt => opt.MapFrom(src=> src.VdsProposalSection));
}
}
Also adding .ReverseMap() creates a reverse mapping
CreateMap<Common.Models.Entities.VDS.QuestionType, Models.Insurance.QuestionType>().ReverseMap();
Startup.cs
In startup.cs -> ConfigurationServices add these lines after services.AddMvc
var autoMapperConfig = new AutoMapper.MapperConfiguration(c =>
{
c.AddProfile(new ApplicationProfile());
});
var mapper = autoMapperConfig.CreateMapper();
services.AddSingleton(mapper);
usage
inject as IMapper mapper
public MakesController(VegaDbContext context, IMapper mapper) ...
Map like below. First parameter is source second is target and in parentheses, we provide the object
this.mapper.Map<Models.ProposalForm.ProposalForm>(proposal);
this.mapper.Map<target>(source);