Home > Software engineering >  Is there a way to dyanmically create multiple maps for Automapper?
Is there a way to dyanmically create multiple maps for Automapper?

Time:05-06

Is there a way to dynamically generate multiple maps? For example, can I map to an array of source and destination values? I am working with a legacy database and one of the tables has over 350 columns. It will be very error prone and labor intensive to map each field manually.

//HOW CAN BELOW INCLUDE OVER 350  MAPPED FIELDS DYNAMICALLY FROM AN ARRAY?
CreateMap<Employee, EditEmployeeModel>()
                .ForMember(dest => dest.ConfirmEmail,
                           opt => opt.MapFrom(src => src.Email));

CodePudding user response:

Basically if the property names are similar then you don't have to map source to destination manually. Automapper will do this automatically. So, if you keep the property names similar then there's no need to map.

But if that's not possible and keeping different names is a necessity then you can use .AfterMap() feature of Automapper. It is simpler than source destination mapping.

public class EditEmployeeMap : IMappingAction<Employee, EditEmployeeModel>
{
    public void Process(Employee source, EditEmployeeModel destination, ResolutionContext context)
    {
         destination.ConfirmEmail = source.Email;
    }
}

Then,

CreateMap<Employee, EditEmployeeModel>().AfterMap<EditEmployeeMap>();

Though the purpose of the above solution is not for this use case, this can make the job more simple for you.

But i would suggest to keep the property name similar, that will save a lot of hastle.

  • Related