0
votes

I'm not too familiar with automapper, but it's been thrown on me by our Software Architect for this project.

The concept is complete encapsulation of volatility. Here's a poorly made Diagram

API/Presentation Layer | Request and Response suffixed objects. (ie, ApplicationCreateRequest)


Business Layer | Home of Domain transfer objects, suffixed DTO. (ie, ApplicationCreateDTO)


Database Layer | Home of Resource Access Objects and entities suffixed RAO and Entity (ie, ApplicationEntity, ApplicationCreateRAO)

I need to convert ApplicationCreateRequests to ApplicationCreateDTO's, as well as convert the Requests Nested objects to DTO's as well.

For example:

public class ApplicationCreateRequest
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public ContactCreateRequest Contact { get; set; }
    public DemographicCreateRequest Demographic { get; set; }
    public EducationCreateRequest Education { get; set; }
    public WorkCreateRequest Work { get; set; }
}

becomes

public class ApplicationCreateDTO
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public ContactCreateDTO Contact { get; set; }
    public DemographicCreateDTO Demographic { get; set; }
    public EducationCreateDTO Education { get; set; }
    public WorkCreateDTO Work { get; set; }
}

The DTO's and Requests have for the most part the same properties.

I've only gotten to work with very basic mappings such as:

CreateMap<ObjectOne, ObjectTwo>(); 
1

1 Answers

0
votes

A easy way to map complex model is to declare, and map them from easiest (with native types eg : strings, int,...) to complex ones.

So, you should create simple mappings for ContactCreateRequest to ContactCreateDTO with CreateMap (and others simplest). Then you will have to create something like :

MapFrom allows you to specify the property (a reason beeing if named differently) to map from. It also allows you to specify a result from a pre-defined mapping, you simply tell it the member you want to Map from...

Mapper.CreateMap<ApplicationCreateRequest, ApplicationCreateDTO>()
    .ForMember(g => g.FirstName, opt => opt.MapFrom(src => src.FirstName));
    .ForMember(g => g.LastName, opt => opt.MapFrom(src => src.LastName));
    .ForMember(g => g.Contact, opt => opt.MapFrom(src => Mapper.Map<ContactCreateRequest,ContactCreateDTO>(g.Contact)));
    .ForMember(g => g.Demographic, opt => opt.MapFrom(src => Mapper.Map<DemographicCreateRequest,DemographicCreateDTO>(g.Demographic)));
    .ForMember(g => g.Education, opt => opt.MapFrom(src => Mapper.Map<EducationCreateRequest,EducationCreateDTO>(g.Education)));
    .ForMember(g => g.Work, opt => opt.MapFrom(src => Mapper.Map<WorkCreateRequest,WorkCreateDTO>(g.Work)));

You can build up by using

.ForMember(g => g.Property, opt => opt.Ignore()); // to ignore the mapping of a property

Handy note, define base mapping before complex ones, otherwise you will have trouble!