Deep level mapping using Automapper
Asked Answered
P

4

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

Platonism answered 21/3, 2013 at 17:58 Comment(1)
To map nested properties with the latest AutoMapper, just use ForPath, instead of ForMember. It works like a charm.Photolysis
G
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));
Goosestep answered 21/3, 2013 at 19:11 Comment(1)
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).Distressful
M
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

Misanthropy answered 21/3, 2013 at 18:56 Comment(0)
C
13

Use ForPath rather than ForMember & It works like magic.

Commemorate answered 25/1, 2019 at 16:54 Comment(1)
Answers suggesting .MapFrom() didn't work for me, but this did.Wenn
P
0
AutoMapper.Mapper.CreateMap<FatherModel ,Father>()
         .ForMember(dest => dest.Son, opt => opt.MapFrom(src => new Son {Id = src.SonId}));

it Works correctly

Paradies answered 16/7, 2023 at 10:2 Comment(1)
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.Reifel

© 2022 - 2024 — McMap. All rights reserved.