如何创建源中的多个属性到目标中的 List 对象的映射?

How do you create mapping of multiple properties in the source to a List object in the destination?

假设我有以下对象:

来源:

public class Scores()
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal ScoreA { get; set; }
    public decimal ScoreB { get; set; }
    public decimal ScoreC { get; set; }
}

目的地:

public class ScoresDto()
{
    public int Id { get; set; }
    public string Name { get; set; }
    public IList<Score> ScoreDetails { get; set; }
}

public class Score()
{
    public string Name { get; set; }
    public decimal Value { get; set; }
}

我了解如何直接映射 1 到 1 属性 映射如下:

public AutomapperProfiles()
{
    CreateMap<Scores, ScoresDto>()
          .ForMember(x => x.Id, opt => opt.MapFrom(y => y.Id))
          .ForMember(x => x.Name, opt => opt.MapFrom(y => y.Name))
}

但是,作为上述映射的一部分,我如何将 ScoreA、ScoreB 和 ScoreC 映射到单独的新 Score 对象中,其中 'Name' 是 属性 的名称,Value 是十进制值,然后让这些分数构成 ScoresDto 上的 ScoreDetails 列表?

您可以创建一个 custom resolver 来完成这项工作;

public class ScoreDetailsResolver : IValueResolver<Scores, ScoresDto, IList<Score>>
{
    public IList<Score> Resolve(Scores source, ScoresDto destination, IList<Score> member, ResolutionContext context)
    {
        destination = destination ?? new ScoresDto();
        destination.ScoreDetails = destination.ScoreDetails ?? new List<Score>();
        destination.ScoreDetails.Add(new Score { Name = source.Name, Value = source.ScoreA });
        destination.ScoreDetails.Add(new Score { Name = source.Name, Value = source.ScoreB });
        destination.ScoreDetails.Add(new Score { Name = source.Name, Value = source.ScoreC });
        return destination.ScoreDetails;
    }
}

并像这样使用它:

CreateMap<Scores, ScoresDto>()
    .ForMember(d => d.ScoreDetails, o => o.MapFrom<ScoreDetailsResolver>());

无需映射其他属性,因为它们会自动映射。