Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map nested child object properties in Automapper

Tags:

c#

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?

like image 493
sensei Avatar asked Sep 04 '17 09:09

sensei


People also ask

Does AutoMapper map nested objects?

With both flattening and nested mappings, we can create a variety of destination shapes to suit whatever our needs may be.

Can AutoMapper map collections?

Polymorphic element types in collectionsAutoMapper supports polymorphic arrays and collections, such that derived source/destination types are used if found.

Does AutoMapper map private properties?

By default, AutoMapper only recognizes public members. It can map to private setters, but will skip internal/private methods and properties if the entire property is private/internal.

Is AutoMapper faster than manual mapping?

Inside this article, it discusses performance and it indicates that Automapper is 7 times slower than manual mapping. This test was done on 100,000 records and I must say I was shocked.


1 Answers

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(); 
like image 95
macostobu Avatar answered Sep 28 '22 02:09

macostobu