Automapper许多一对多stackoverflowexce

Automapper许多一对多stackoverflowexce

本文介绍了Automapper许多一对多stackoverflowexception的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个堆栈溢出以下映射:

  Mapper.CreateMap<家长,ParentViewModel>()
.ForMember(X => x.Children,O => o.MapFrom(X => x.Children.ConvertToChildrenViewModel()));

Mapper.CreateMap<儿童,ChildrenViewModel>()
.ForMember(X => x.Parents,O => o.MapFrom(X => x.Parents.ConvertToParentViewModel ()));



我明白为什么会这样,显然这里的无限循环。我怎么得到这个在automapper工作?我需要家长了解自己的孩子和他们的孩子了解自己的父母。我会创建另一个视图模型 Children.Parents 不包含父母?。孩子属性



扩展方法的例子,同样为孩子:

 公共静态的IList< ParentViewModel> ConvertToParentViewModel(这IEnumerable的<家长和GT;家长)
{
返回Mapper.Map<&IList的LT; ParentViewModel>>(父母);
}


解决方案

AutoMapper并跟踪什么映射,但只有在一个单一的地图调用,而不是多个外部调用Mapper.Map的情况下。



您应该不需要在任映射配置的ForMember件。如果删除,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);
        }
解决方案

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.

这篇关于Automapper许多一对多stackoverflowexception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 04:44