Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with ignoring base class property in child classes mappings using Automapper

Tags:

automapper

I have a scenario where I would like to ignore some properties of classes defined in base class.

I have an initial mapping like this

   Mapper.CreateMap<Node, NodeDto>()
                .Include<Place, PlaceDto>()
                .Include<Asset, AssetDto>();

Then I customised it more like this to ignore one of the properties defined in base class NodeDto

 Mapper.CreateMap<Node, NodeDto>()
                .ForMember(dest => dest.ChildNodes, opt => opt.Ignore());

However when I try to map, Place to PlaceDto or Asset to AssetDto, the ChildNodes property does not get ignored. So I ended up doing soething like this

  Mapper.CreateMap<Node, NodeDto>()
                .ForMember(dest => dest.ChildNodes, opt => opt.Ignore());
            Mapper.CreateMap<Place, PlaceDto>()
                .ForMember(dest => dest.ChildNodes, opt => opt.Ignore());
            Mapper.CreateMap<Asset, AssetDto>()
                .ForMember(dest => dest.ChildNodes, opt => opt.Ignore());

Since I have lots of child classes for NodeDto, the above process is cumbersome, and I would like to know if there is a better approach?

Thanks Nabeel

like image 862
nabeelfarid Avatar asked Jul 26 '10 16:07

nabeelfarid


1 Answers

It gets even more cumbersome if you then decide that you want to ignore not just 1, but 2, 3 or maybe even more properties from the base class. It might not help you much in this case and I'm sure 9 months on you've probably found a solution already, but for the benefit of anyone else stumbling across this question an extension method could reduce some of the complexity.

    public static class MappingExtensions
    {
        public static IMappingExpression<Node, NodeDto> MapNodeBase<Node, NodeDto>(
            this IMappingExpression<Node, NodeDto> mappingExpression)
        {
            // Add your additional automapper configuration here
            return mappingExpression.ForMember(
                dest => dest.ChildNodes, 
                opt => opt.Ignore()
            );
        }
    }

Which you would then call thus:

Mapper.CreateMap<Node, NodeDto>()
            .MapNodeBase()
            .Include<Place, PlaceDto>()
            .Include<Asset, AssetDto>();
like image 61
Matt B Avatar answered Sep 25 '22 05:09

Matt B