c# - 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
.
解决方案
我想我找到了我正在寻找的解决方案。使用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++;
}
})
推荐阅读
- pip - pip install tensorflowjs 时出错 — 由于 EnvironmentError 无法安装软件包:[Errno 2] 没有这样的文件或目录:
- mysql - 如何在 MySQL 中每个条件选择一行?
- python - 如何设置断点()来启动 IPython shell?(Python 3.7+)
- docker - 如何正确配置 Dockerfile 以在 Google Cloud Run 上运行?
- php - 我有一个关于 wordpress 钩子和过滤器的问题
- c# - devops 中单元测试的重复
- java - 我可以在同一方法上混合使用 @Cacheable 和 @Transactional 等两个 Spring 声明性功能吗?
- c# - 如何将 Objective-c 回调块转换为 C#?
- java - 在 Reactor 应用程序中测试对 Flux 的背压应用程序
- react-native - 为什么'i'不在for循环中增加?