简体   繁体   中英

Default mapping configuration for inherited classes in AutoMapper

Is it possible to create a default destination mapping in AutoMapper ?

Source classes:

class SourceA { 
  public string X { get; set; } 
}
class SourceB { 
  public string Y { get; set; } 
}

Destination classes:

class DestBase { 
  public List<string> Z { get; set; }
}
class DestA : DestBase { 
  public string X { get; set; } 
}
class DestB : DestBase { 
  public string Y { get; set; } 
}

And the mapping configuration contains the following:

cfg.CreateMap<SourceA, DestA>()
  .ForMember(dest => dest.Z, src => src.MapFrom(s => null));
cfg.CreateMap<SourceB, DestB>()
  .ForMember(dest => dest.Z, src => src.MapFrom(s => null));

Is it possible to create a default mapping for all destination classes inheriting the DestBase to avoid the repeated .ForMember(...) lines ?

eg. something like:

cfg.CreateMap<object, DestBase>
   .ForMember(dest => dest.Z, src => src.MapFrom(s => new List<string>()));

In principle yes, with the Include method, but there is a caveat.

If you define a map from source type object , this map would match all types. Maybe you can introduce an interface ISource for the source types that should be affected by this mapping.

So it could look like this:

    class SourceA : ISource { 
        public string X { get; set; } 
    }

    class SourceB : ISource { 
        public string Y { get; set; } 
    }

    cfg.CreateMap<ISource, DestBase>
       .Include<SourceA, DestA>
       .Include<SourceB, DestB>
       .Include<SourceC, DestC>
       .ForMember(dest => dest.Z, , o => o.MapFrom(src => new List<string>()));

    cfg.CreateMap<SourceA, DestA>()
        .ForMember(dest => dest.X, o => o.MapFrom(src => src.X));

    cfg.CreateMap<SourceB, DestB>()
        .ForMember(dest => dest.Y, o => o.MapFrom(src => src.Y));

    // still need to create a map even if no additional properties are to be mapped
    cfg.CreateMap<SourceC, DestC>();

Note that you still need to create maps for all included types, even if there are no additional properties to map.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM