简体   繁体   中英

AutoMapper failing on on double

I have the following classes

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; }
}

And I have the following AutoMapper config

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

When I try to convert between the two ie

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

automapper throws the following error:

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

Mapping types:
Estimation -> Double

(note that it throws the same error if I try the reverse conversion).
I tried doing explicit mapping for the properties, however this did not fix the issue.

If I specify the double conversion

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

It works and properly converts between the two types.

How come I have to specify this specific conversion for the classes?

When using constructor arguments, you need to create explicit mappings that outline those constructor arguments with .ConstructUsing() (this example is in version 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM