从双重映射

时间:2016-07-26 19:06:10

标签: c# .net type-conversion automapper automapper-5

使用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处理的一个超级简单案例,但我似乎无法修复错误。任何建议都表示赞赏。

1 个答案:

答案 0 :(得分:0)

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

CreateMap<double, Distance>().ConvertUsing(src => new Distance(src, "Inch"));