我正在使用 AutoMapper 6.2.2 将 View 模型转换为 dto 模型。 View 模型有 2 个匹配字段和一个不匹配字段,可以转换为其他 7 个字段。问题在于,不匹配的字段是使用生成所有 7 个备用字段的静态方法进行解析的。因此,我如何才能一次性将源 Value
字段映射到 7 个目标成员,而不是为 7 个单独字段中的每一个字段发出 ForMember
并每次调用静态转换方法无需多次实例化它?
this.CreateMap<MyViewModel, MyModel>()
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name))
.ForMember(dest => dest.Description, opt => opt.MapFrom(src => src.Description))
.ForMember(dest => dest.FieldA, opt => opt.MapFrom(src => StaticHelper.Parse(src.Value).FieldA))
// More instances of the same static helper unnecessarily instantiated.
.ForMember(dest => dest.FieldG, opt => opt.MapFrom(src => StaticHelper.Parse(src.Value).FieldG));
最佳答案
使用 ConstructUsing
,您可以构建初始对象并通过静态方法从一个源字段映射 7 个字段,然后让 AutoMapper 映射其余字段或继续使用 ForMember
手动映射它们。
关于c# - 更高效的自定义 map 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48895431/