[英]Automapper - Mapping the index into a property of collection
I'm mapping a domain model to a DTO and vice versa.我正在将域模型映射到 DTO,反之亦然。 I'm trying to configure my API to accept a DTO with a collection, where the order of that collection will map to a int Sequence
in my domain object for persistence.我正在尝试将我的 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++;
;
Is such a thing possible in Automapper, or would I have to write my own ConstructUsing()
method to do this logic? Automapper 中是否可以实现这样的事情,还是我必须编写自己的ConstructUsing()
方法来执行此逻辑? I'm hesitant to use ConstructUsing()
because I have a mapping specified for the Field DTO and I don't want to duplicate that logic.我对使用ConstructUsing()
犹豫不决,因为我为 Field DTO 指定了一个映射,我不想复制该逻辑。
I also would like to be able to configure it so that when I'm going back to my DTO ( Model
-> ModelView
) that I can insert the Field
s into the collection in the order specified by Sequence
.我还希望能够对其进行配置,以便当我返回到我的 DTO( Model
-> ModelView
)时,我可以按照Sequence
指定的Sequence
将Field
插入到集合中。
I think I found the solution I was looking for.我想我找到了我正在寻找的解决方案。 Using AfterMap()
I'm able to override these values from being mapped directly:使用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++;
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.