Deep level mapping using Automapper

    AutoMapper.Mapper.CreateMap<FatherModel, Father>()
                     .ForMember(x => x.Son, opt => opt.ResolveUsing(model => new Son() {Id = model.SonId}));

if it's getting more complex you can write a ValueResolver class, see example here- https://docs.automapper.org/en/stable/Custom-value-resolvers.html


Use ForPath rather than ForMember & It works like magic.


This will work both for mapping to a new or to an existing object.

Mapper.CreateMap<FatherModel, Father>()
    .ForMember(x => x.Son, opt => opt.MapFrom(model => model));
Mapper.CreateMap<FatherModel, Son>()
    .ForMember(x => x.Id, opt => opt.MapFrom(model => model.SonId));

Tags:

C#

Automapper