使用自动映射器忽略第 2 级 child

Ignore 2nd level child using automapper

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(); });

获取错误"Missing type map configuration or unsupported mapping for GrandChildSource"

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

除非我遗漏了什么,否则使用直接映射应该相当简单:

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

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

如果有比这更复杂的问题,请说明问题所在。