Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper many-to-many stackoverflowexception

Tags:

c#

automapper

I'm getting a stack overflow for the following mapping:

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, clearly an infinite loop here. How am I supposed to get this to work in automapper? I need parents to know about their children and their children to know about their parents. Would I have to create another ViewModel for Children.Parents that doesn't contain the Parents.Children property?

Extension methods example, similarly for children:

public static IList<ParentViewModel> ConvertToParentViewModel(this IEnumerable<Parent> parents)
        {
            return Mapper.Map<IList<ParentViewModel>>(parents);
        }
like image 587
spaceagestereo Avatar asked Dec 22 '22 07:12

spaceagestereo


1 Answers

There's a MaxDepth setting you can use for recursive mappings. I've never used it before, but it may help you out. You set it on the type mappings:

Mapper.CreateMap(...).MaxDepth(5)
like image 153
PatrickSteele Avatar answered Jan 09 '23 04:01

PatrickSteele