Automapper, mapping to a complex object

2019-08-21 05:12发布

问题:

I have 2 classes i'm trying to map namely

1) Entity 2) DTO

I'm trying to map Entity.Foo to DTO.Child.Foo

Obviously the below will not work, how do I achieve this. I need to create a new instance of Child and then attach that to the Mapper and then set the Foo property but my AutoMapper skills are not that good!

Mapper.CreateMap<Entity, DTO>()
 .ForMember("Child.Foo", m => m.MapFrom(entity => entity.Foo))

回答1:

Mapper.CreateMap<Entity, DTO>()
    .ForMember(d => d.Foo, 
        o => o.ResolveUsing(s => new DTO.Child { Foo = s.Foo }))

// comment