41

I am trying to map objects with multi-level members: these are the classes:

 public class Father
    {
        public int Id { get; set; }
        public Son Son { get; set; }
    }

    public class FatherModel
    {
        public int Id { get; set; }
        public int SonId { get; set; }
    }

    public class Son
    {
        public  int Id { get; set; }
    }

This is how I try automap it:

 AutoMapper.Mapper.CreateMap<FatherModel , Father>()
                      .ForMember(dest => dest.Son.Id, opt => opt.MapFrom(src => src.SonId));

this is the exception that I get:

Expression 'dest => Convert(dest.Son.Id)' must resolve to top-level member and not any child object's properties. Use a custom resolver on the child type or the AfterMap option instead. Parameter name: lambdaExpression

Thanks

jww
  • 97,681
  • 90
  • 411
  • 885
SexyMF
  • 10,657
  • 33
  • 102
  • 206

4 Answers4

47

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));
Allrameest
  • 4,364
  • 2
  • 34
  • 50
  • 7
    The important part of this answer is the mapping of the Son property to the model, that is what forces the use of the second mapping (line 2). – Steve Jan 26 '15 at 10:54
21
    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

DeanOC
  • 7,142
  • 6
  • 42
  • 56
Maxim
  • 7,268
  • 1
  • 32
  • 44
13

Use ForPath rather than ForMember & It works like magic.

Teja Swaroop
  • 185
  • 1
  • 12
0
AutoMapper.Mapper.CreateMap<FatherModel ,Father>()
         .ForMember(dest => dest.Son, opt => opt.MapFrom(src => new Son {Id = src.SonId}));

it Works correctly

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 19 '23 at 00:33