c# – 从double映射

使用Automapper 5.0.2.0我试图从TypeA映射到TypeB:

public class TypeA
{
    public double Length { get; set; }
}


public class TypeB
{
    public Distance Length { get; set; }
}

我假设长度以英寸为单位并创建了这个映射配置文件:

public class CalculationProfile : Profile
{
    public CalculationProfile()
    {
       CreateMap<TypeA, TypeB>()
            .ForMember(dest => dest.Length,
                       opt => opt.MapFrom(src => new Distance(src.Length, "Inch")))
    }
}

我这样使用它:

Mapper.Initialize(configuration =>
{
    configuration.AddProfile(new CalculationProfile());
});

var typeA = new TypeA(){Length = 1.0};

var typeB = Mapper.Map<TypeB>(typeA);

但是,最后一行会引发以下错误:

AutoMapper.AutoMapperMappingException was unhandled by user code
  HResult=-2146233088
  Message=Missing type map configuration or unsupported mapping.

Mapping types:
Double -> Distance
System.Double -> UnitClassLibrary.DistanceUnit.Distance
  Source=Anonymously Hosted DynamicMethods Assembly
  StackTrace:
       at lambda_method(Closure , Double , Distance , ResolutionContext )
       at lambda_method(Closure , Object , Object , ResolutionContext )
       at TestProject.AutoMapperTests.FromPersistenceObjectToCalculationModel_Test() in C:\...\AutoMapperTests.cs:line 69
  InnerException: 

对于Automapper来说,这似乎是一个非常简单的案例,但是我似乎无法修复错误.任何建议表示赞赏.

解决方法:

你真的想要在double和distance之间进行新的类型转换:

CreateMap<double, Distance>().ConvertUsing(src => new Distance(src, "Inch"));
上一篇:c# – AutoMapper – 如何映射到三级深度


下一篇:c# – 如何让Automapper通过Id字段上的内连接获取相关记录,而不是外键?