【问题标题】:Automapper - Mapping the index into a property of collectionAutomapper - 将索引映射到集合的属性
【发布时间】:2020-02-19 01:05:28
【问题描述】:

我将域模型映射到 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) 时,我可以按照指定的顺序将 Fields 插入到集合中Sequence.

【问题讨论】:

    标签: c# automapper


    【解决方案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++;
            }
        })
    

    【讨论】:

    • 您可以使用ReverseMap 而不是添加第二个映射。顺便说一句,您的问题不包含ModelView 的定义,对我来说,这个要求有点难以理解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多