Automatic multiuser stackoverflowexception

I get a stack overflow for the following display:

Mapper.CreateMap<Parent, ParentViewModel>() .ForMember(x => x.Children, o => o.MapFrom(x => x.Children.ConvertToChildrenViewModel())); Mapper.CreateMap<Children, ChildrenViewModel>() .ForMember(x => x.Parents, o => o.MapFrom(x => x.Parents.ConvertToParentViewModel())); 

I understand why this is happening, obviously an endless loop here. How should I make this work in automapper? I need parents to know about their children and their children in order to find out about their parents. Should I create another ViewModel for Children.Parents that does not contain the Parents.Children property?

An example of an extension method, similar for children:

 public static IList<ParentViewModel> ConvertToParentViewModel(this IEnumerable<Parent> parents) { return Mapper.Map<IList<ParentViewModel>>(parents); } 
+4
source share
2 answers

AutoMapper monitors the display, but only in the context of a single map call, not multiple external Mapper.Map calls.

You do not need to use the ForMember element for any mapping configuration. If you remove this, AutoMapper will traverse the parent / child relationships and keep track of what has already been displayed.

+3
source

There is a MaxDepth parameter MaxDepth that you can use for recursive mappings. I have never used it before, but it can help you. You set it to type mappings:

 Mapper.CreateMap(...).MaxDepth(5) 
+7
source

All Articles