首页 > 解决方案 > Automapper - 将索引映射到集合的属性

问题描述

我将域模型映射到 DTO,反之亦然。我正在尝试将我的 API 配置为接受带有集合的 DTO,其中该集合的顺序将映射到int Sequence我的域对象中的 a 以实现持久性。

public class Model {
    public ICollection<Fields> Fields { get; set; }
}
public class Field {
    public int Sequence { get; set; }
}
CreateMap<ModelView, Model>()
    .ForMember(x => x.Fields, opt => opt...)
    // here I want to specify that currentField.Sequence = Model.Fields.IndexOf(currentField)
    //     , or to set it equal to some counter++;
    ;

在 Automapper 中是否有可能,还是我必须编写自己的ConstructUsing()方法来执行此逻辑?我犹豫要不要使用ConstructUsing(),因为我为 Field DTO 指定了一个映射,并且我不想重复该逻辑。

我还希望能够对其进行配置,以便当我回到我的 DTO ( Model-> ModelView) 时,我可以Field按照Sequence.

标签: c#automapper

解决方案


我想我找到了我正在寻找的解决方案。使用AfterMap()我可以直接映射这些值:

CreateMap<Model, ModelView>()
    .AfterMap((m, v) =>
    {
        v.Fields = v.Fields?.OrderBy(x => x.Sequence).ToList(); 
        //ensure that the DTO has the fields in the correct order
    })
    ;


CreateMap<ModelView, Model>()
    .AfterMap((v, m) =>
    {
        //override the sequence values based on the order they were provided in the DTO
        var counter = 0;
        foreach (var field in m.Fields)
        {
            field.Sequence = counter++;
        }
    })

推荐阅读