手动配置对象映射,虽然麻烦但是具有可测试的有点。 One of the inspirations behind AutoMapper was to eliminate not just the custom mapping code, but eliminate the need for manual testing(AutoMapper虽然淘汰了手动配置映射,但是仍然保留了必须的可测试性)。因为映射是基于约定的,你仍需要测试你的配置。

AutoMapper 以 AssertConfigurationIsValid 方法的形式,提供配置测试。例如:

  1. public class Source
  2. {
  3. public int SomeValue { get; set; }
  4. }
  5. public class Destination
  6. {
  7. public int SomeValuefff { get; set; }
  8. }
  9. // 测试
  10. var configuration = new MapperConfiguration(cfg =>
  11. cfg.CreateMap<Source, Destination>());
  12. configuration.AssertConfigurationIsValid();

执行测试代码会产生 AutoMapperConfigurationException 错误。AutoMapper检查以确保每个目标类型成员在源类型上都有一个对应成员。

重写配置错误

三种方式来解决这个错误:

自定义解析器(不推荐):

  1. public interface IValueResolver<in TSource, in TDestination, TDestMember>
  2. {
  3. TDestMember Resolve(TSource source, TDestination destination, TDestMember destMember, ResolutionContext context);
  4. }
  5. public class CustomResolver : IValueResolver<Source, Destination, int>
  6. {
  7. // 可能不太对
  8. public int Resolve(Source source, Destination destination, int member, ResolutionContext context)
  9. {
  10. return source.SomeValue;
  11. }
  12. var configuration = new MapperConfiguration(cfg =>
  13. cfg.CreateMap<Source, Destination>()
  14. .ForMember(dest => dest.Total, opt => opt.MapFrom<CustomResolver>()));
  15. configuration.AssertConfigurationIsValid();

投影:

  1. var configuration = new MapperConfiguration(cfg =>
  2. cfg.CreateMap<Source, Destination>());
  3. .ForMember(dest => dest.SomeValuefff, opt => opt.MapFrom(src => src.SomeValue))

忽视:

  1. var configuration = new MapperConfiguration(cfg =>
  2. cfg.CreateMap<Source, Destination>());
  3. .ForMember(dest => dest.SomeValuefff, opt => opt.Ignore())