c# - 更高效的自定义 map 配置

标签 c# automapper asp.net-core-2.0

我正在使用 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/

相关文章:

c# - AutoMapper Custom Resolver 在构造函数中请求可选参数

automapper - ValueInjecter问题

angular - XSRF antiforgery : Asp.Net Core 2 WebApi(不是 MVC)+ Angular 的单独服务器是可能的吗?

c# - Core 2 在 API Controller 上授权

c# - LazyInitializer.EnsureInitialized 中的 volatile 局部变量?

c# - AutoMapper:根据枚举的值将类映射到 View 模型

c# - 我如何最小起订量 System.IO.FileInfo 类...或任何其他没有接口(interface)的类?

c# - 没有 MVC 的 .Net Core 2 路由

c# - Web 应用程序中用于周期性任务的子系统

c# - 不同部署槽中的计时器触发的 Azure Webjob