手动配置对象映射,虽然麻烦但是具有可测试的有点。 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 方法的形式,提供配置测试。例如:
public class Source
{
public int SomeValue { get; set; }
}
public class Destination
{
public int SomeValuefff { get; set; }
}
// 测试
var configuration = new MapperConfiguration(cfg =>
cfg.CreateMap<Source, Destination>());
configuration.AssertConfigurationIsValid();
执行测试代码会产生 AutoMapperConfigurationException 错误。AutoMapper检查以确保每个目标类型成员在源类型上都有一个对应成员。
重写配置错误
三种方式来解决这个错误:
自定义解析器(不推荐):
public interface IValueResolver<in TSource, in TDestination, TDestMember>
{
TDestMember Resolve(TSource source, TDestination destination, TDestMember destMember, ResolutionContext context);
}
public class CustomResolver : IValueResolver<Source, Destination, int>
{
// 可能不太对
public int Resolve(Source source, Destination destination, int member, ResolutionContext context)
{
return source.SomeValue;
}
var configuration = new MapperConfiguration(cfg =>
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Total, opt => opt.MapFrom<CustomResolver>()));
configuration.AssertConfigurationIsValid();
投影:
var configuration = new MapperConfiguration(cfg =>
cfg.CreateMap<Source, Destination>());
.ForMember(dest => dest.SomeValuefff, opt => opt.MapFrom(src => src.SomeValue))
忽视:
var configuration = new MapperConfiguration(cfg =>
cfg.CreateMap<Source, Destination>());
.ForMember(dest => dest.SomeValuefff, opt => opt.Ignore())