4

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

4

1 回答 1

0

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

CreateMap<double, Distance>().ConvertUsing(src => new Distance(src, "Inch"));
于 2016-07-27T14:33:24.493 回答