问题
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);
}
回答1:
AutoMapper does keep track of what's mapped, but only in the context of a single Map call, not multiple external calls to Mapper.Map.
You shouldn't need the ForMember piece on either mapping configuration. If you remove that, AutoMapper will traverse the parent/child relationships and keep track of what has already been mapped.
回答2:
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)
来源:https://stackoverflow.com/questions/7895399/automapper-many-to-many-stackoverflowexception