Automapper-将索引映射到集合的属性

时间:2020-02-18 16:35:19

标签: c# automapper

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

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指定的顺序收集。

1 个答案:

答案 0 :(得分:1)

我想我找到了我想要的解决方案。使用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++;
        }
    })
相关问题