使用automapper忽略二级孩子

时间:2015-12-22 17:59:02

标签: asp.net-mvc entity-framework-6 automapper-4

public class Source
{
   public ChildSource ChildSource { get; set; }
   //some other properties 
}

public class ChildSource
{
   public List<GrandChildSource> GrandChildSources { get; set; }
   //some other properties
}

public class GrandChildSource
{
   Public ChildSource ChildSource { get; set; }
   //some other properties
}

And Dto classes:

public class SourceDto
{
   public ChildSourceDto ChildSource { get; set; }
   //some other properties
}

public class ChildSourceDto
{
   public List<GrandChildSourceDto> GrandChildSources { get; set; }
   //some other properties
}

public class GrandChildSourceDto
{
   Public ChildSourceDto ChildSource { get; set; }
   //some other properties
}

我想将source / childsource类映射到dto类并忽略GrandChildSources属性。

我尝试过使用UseDestinationValue和Ignore,但似乎无法正常工作。

Mapper.CreateMap<Source, SourceDto>()
                .ForMember(dest => dest.ChildSource, opt => { opt.UseDestinationValue(); opt.Ignore(); })
                .AfterMap((source, destination) => Mapper.Map(source.ChildSource, destination.ChildSource));

Mapper.CreateMap<ChildSource, ChildSourceDto>()
                .ForMember(d => d.GrandChildSources, opt => { opt.UseDestinationValue(); opt.Ignore(); });

获取错误“缺少类型映射配置或GrandChildSource不支持的映射”

PS:LazyLoadingEnabled设置为True。我决定在获得Stack溢出异常后忽略GrandChildSources属性,因为它有循环引用。

1 个答案:

答案 0 :(得分:1)

除非我遗漏了某些东西,否则这应该是相当简单的直接映射:

Mapper.CreateMap<Source, SourceDto>();
Mapper.CreateMap<ChildSource, ChildSourceDto>()
    .ForMember(dest => dest.GrandChildSources, opt => opt.Ignore());

或者,您可以忽略GrandChildSourceDto上的ChildSource属性,以避免出现循环引用问题。

如果有比这更复杂的事情,请澄清问题所在。