AutoMapper在双重故障时失败

时间:2015-10-06 03:46:28

标签: c# automapper

我有以下课程

public class EstimationDTO
{
    public EstimationDTO() { }
    public EstimationDTO(double best, double mostLikely, double worst)
    {
        this.BestEffort = best;
        this.MostLikelyEffort = mostLikely;
        this.WorstEffort = worst;
    }
    public double BestEffort { get; set; }
    public double MostLikelyEffort { get; set; }
    public double WorstEffort { get; set; }
}
public class Estimation
{
    public Estimation() { }
    public Estimation(double best, double mostLikely, double worst)
    {
        this.BestEffort = best;
        this.MostLikelyEffort = mostLikely;
        this.WorstEffort = worst;
    }
    public double BestEffort { get; set; }
    public double MostLikelyEffort { get; set; }
    public double WorstEffort { get; set; }
}

我有以下AutoMapper配置

Mapper.CreateMap<EstimationDTO, Estimation>();
Mapper.CreateMap<Estimation, EstimationDTO>();

当我尝试在两者之间进行转换时。

var x = Mapper.Map<EstimationDTO>(new Estimation{ BestEffort = 0.1, MostLikelyEffort = 0.2, WorstEffort = 0.3 });

automapper会抛出以下错误:

AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping.

Mapping types:
Estimation -> Double

(请注意,如果我尝试进行反向转换,则会抛出相同的错误) 我尝试对属性进行显式映射,但这并没有解决问题。

如果我指定双转换

Mapper.CreateMap<EstimationDTO, double>();
Mapper.CreateMap<Estimation, double>();

它可以在两种类型之间正常转换。

为什么我必须为类指定此特定转换?

1 个答案:

答案 0 :(得分:2)

使用构造函数参数时,需要创建显式映射,用.ConstructUsing()概述这些构造函数参数(此示例在版本4.0.4中)。

void Main()
{
    Mapper.CreateMap<EstimationDTO, Estimation>()
        .ConstructUsing(
            (Func<EstimationDTO, Estimation>)(x => new Estimation(0.1, 0.2, 0.3)));

    Mapper.CreateMap<Estimation, EstimationDTO>()
        .ConstructUsing(
            (Func<Estimation, EstimationDTO>)(x => new EstimationDTO(0.1, 0.2, 0.3)));

    var mapped = Mapper.Map<EstimationDTO>(
        new Estimation{ BestEffort = 0.1, MostLikelyEffort = 0.2, WorstEffort = 0.3 });

    mapped.Dump();
}