0

I have a problem with my AutoMapper configuration, I can map for one level but I don't know if there exists a way to map for two levels

I have:

Class A 
{
    public int id {get; set;}
    public string nom {get; set;}
    public B Bprop {get; set;}
}

Class B
{
    public int id {get; set;}
    public string nom {get; set;}
    public C Cprop {get; set;}
}

Class C 
{
    public int id {get; set;}
    public string nom {get; set;}
}

My code for configuration is below, and it works if I delete Cprop from class B:

 MapperTools<DatabaseA, A> mapperToolsService =
     new MapperTools<DatabaseA, A>(MappingHelper);

 mapperToolsService.MappingConfig.Configuration.CreateMap<DatabaseA, A>()
     .ForMember(dest => dest.Bprop , opt => opt.MapFrom(src => src.DatabaseB));

 mapperToolsService.MappingConfig.Configuration.CreateMap<DatabaseB,B>();

Please, what is wrong with my code?

1 Answer 1

2

Actually this is three level mapping.

Add mapping for class C as you have for class B. Extend mapping for class B to cover Cprop.

Assuming that DatabaseX have Xprop field corresponding to Xprop field in target classes(A, B, C) it should look like this:

Mapper.CreateMap<DatabaseA, A>()
  .ForMember(dest => dest.Bprop , opt => opt.MapFrom(src => src.Bprop));

Mapper.CreateMap<DatabaseB,B>()
  .ForMember(dest => dest.Cprop , opt => opt.MapFrom(src => src.Cprop));

Mapper.CreateMap<DatabaseC, C>();

Here is working example: https://github.com/st4hoo/Automapper3LevelMappingExample

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.