Problem with ignoring base class property in child class mappings using Automapper

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

I have an initial display like this

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

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

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

However, when I try to match, Place to PlaceDto or Asset for AssetDto, the ChildNodes property is not ignored. So I finished doing something 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 many child classes for NodeDto, the process described above is cumbersome and I would like to know if there is a better approach?

Thanks Nabil

+5
source share
3 answers

, , , automapper

+2

, , 1, 2, 3 , , . , , 9 , , , , - , .

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

:

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

. mappings.xml .

<mappings>
  <mapping name="EntityOne">
    <configuration name="Flat">
      <ignore name="ChildCollectionOne"/>
      <ignore name="ChildCollectionTwo"/>
      <ignore name="ChildCollectionThree"/>
    </configuration>
    <configuration name="Full">
      <include name="ChildCollectionOne" configuration="Flat" type="One"/>
      <include name="ChildCollectionTwo" configuration="Flat" type="Two"/>
      <include name="ChildCollectionThree" configuration="Flat" type="Three"/>
    </configuration>
  </mapping>
</mappings>

AutoMapperUtilis xml Automapper .

:

AutoMapperUtil.Init(typeof(EntityOne),typeof(EntityOneDto), AutoMapperUtilLoadType.Flat);

, ChildCollections .

Using these descriptions, we can choose between a flat or full configuration depending on our use case. We use AutoMapper to map between the nHibernate and Dto`s objects that are used with Ria Services, and we are very pleased with this solution.

+2
source

All Articles