asp.net-mvcentity-framework-6automapper-4

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
}

I would like to map source/childsource classes to dto classes and ignore GrandChildSources property.

I have tried using UseDestinationValue and Ignore but it seems to be not working.

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

Getting error "Missing type map configuration or unsupported mapping for GrandChildSource"

PS: LazyLoadingEnabled is set to True. I decided to ignore GrandChildSources property after getting Stack overflow exception as it has got circular reference .


Solution

  • Unless I'm missing something, this should be fairly simple with straightforward mappings:

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

    Alternately you could ignore the ChildSource property on GrandChildSourceDto to avoid your circular reference problem.

    If there's something more complex than this, please clarify what the problem is.