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(),因为我为字段DTO指定了一个映射,并且我不想重复该逻辑。

我还希望能够对其进行配置,以便在返回DTO(Model->ModelView(时,可以按Sequence指定的顺序将Field插入集合中。

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

最新更新