简体   繁体   中英

How to map nested child object properties in Automapper

I have current map:

CreateMap<Article, ArticleModel>()
    .ForMember(dest => dest.BaseContentItem, opts => opts.MapFrom(src => src.BaseContentItem))
    .ForMember(dest => dest.BaseContentItem.TopicTag, opts => opts.MapFrom(src => src.BaseContentItem.TopicTag))
    .ForMember(dest => dest.MainImage, opts => opts.MapFrom(src => src.MainImage))
    .ReverseMap();

The error I get is:

System.ArgumentException: 'Expression 'dest => dest.BaseContentItem.TopicTag' 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.'

How can I map this?

This should work. Use ForPath instead of ForMember

CreateMap<Article, ArticleModel>()
    .ForMember(dest => dest.BaseContentItem, opts => opts.MapFrom(src => src.BaseContentItem))
    .ForPath(dest => dest.BaseContentItem.TopicTag, opts => opts.MapFrom(src => src.BaseContentItem.TopicTag))
    .ForMember(dest => dest.MainImage, opts => opts.MapFrom(src => src.MainImage))
    .ReverseMap();

If anyone has an issue, I had strange.

I created maps for all children correctly in separate mapping profiles. The issue was that one of those child models had a type of TopicTag itself, so it made stack overflow. I removed that unnecessary field and it maps correctly now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM