Search code examples
c#mappingautomapperautomapper-3

Automapper Many to one map configuration


I want to map 3 different classes into a single DTO, each property have the same name on the source and the destination, the classes are the following:

  • User
  • Candidate
  • Portfolio

this is the DTO and how I want to map my objects:

public class CandidateTextInfo
    {
        public string ProfilePicture { get; set; }   //-->User
        public ObjectId UserId { get; set; }         //-->User
        public string Name { get; set; }             //--> Candidate
        public string Headline { get; set; }         //--> Candidate
        public Gender Gender { get; set; }           //--> Candidate
        public byte Rating { get; set; }             //--> Candidate
        public bool IsCompany { get; set; }          //--> Candidate
        public string[] Tags { get; set; }           //--> Portafolio
        public string[] Categories { get; set; }     //--> Portafolio
        public string ExecutiveSummary { get; set; } //--> Portafolio
        public HourlyRate HourlyRate{ get; set; }    //--> Candidate
    }

I've been looking in SO and I found this solution but I don't get the method ConstructUsing

so how can I do to have a many to one mapping, is that possible, if not any workaround?


Solution

  • Automapper's ConstructUsing is useful to build one property from custom code. In your case it is not really necessary. You just need to create the maps from your objects to your DTO. Then map each object instance to the same DTO instance.

    However since Automapper wants each property of the destination object to be defined in order to ensure that the destination is fully specified you will need to configure each mapping with the properties not existing in the source object as ignored

    CreateMap<Candidate, CandidateTextInfo>()
    .ForMember(x=> x.ProfilePicture, opt => opt.Ignore())
    .ForMember(... 
    // repeat for all destination properties not existing in source properties
    

    If this is too much boilerplate code, many solutions are explored on stack overflow, among which this one looks promising: AutoMapper: "Ignore the rest"? (look at Robert Schroeder's answer)