自动映射器映射对象

编程入门 行业动态 更新时间:2024-10-28 13:13:32
本文介绍了自动映射器映射对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

基于此问题的此附加要求一个来源到多个目的地

This additional requirement based on this question one source to mutiple destination

class Dest1 { string prop1; string prop2; string prop3; pubic List<Dest3> Dests3 {get;set;} } class Dest3 { string prop7; string prop8; } class Source2 { string prop7; string prop8; }

  • 我需要在自动映射器中将Source2映射到Dest1(Dest3是一个列表,也需要映射)
  • 我的制图课:(不起作用)

    My mappping class:(not working)

    CreateMap<Source2, Dest3>(); CreateMap<Source2, Dest1>() .ForMember(d => d.Dests3 , opt => opt.MapFrom(s => s));

    推荐答案

    因此,假设发生此映射时,Dests3应该是单个项目列表,则其配置应类似于以下内容:

    So, assuming that when this mapping occurs Dests3 should be a single item list, the configuration for this should look something like this:

    var configuration = new MapperConfiguration(cfg => // Mapping Config cfg.CreateMap<Source2, Dest1>() .ForMember(dest => dest.prop1, opt => opt.Ignore()) .ForMember(dest => dest.prop2, opt => opt.Ignore()) .ForMember(dest => dest.prop3, opt => opt.Ignore()) .ForMember(dest => dest.Dests3, opt => opt.MapFrom(src => new List<Dest3> { new Dest3 { prop7 = src.prop7, prop8 = src.prop8 } })); // Check AutoMapper configuration configuration.AssertConfigurationIsValid();

    然后,您可以使用映射器在需要的任何地方处理映射,就像这样:

    Then, you can use the mapper to handle the mapping wherever you need, like so:

    public class Foo { private IMapper _mapper; public Foo(IMapper mapper) { _mapper = mapper; } // Map Source2 -> Dest1 public Dest1 Bar(Source2 source) { return _mapper.Map<Dest1>(source); } }

    更多推荐

    自动映射器映射对象

    本文发布于:2023-11-04 12:01:48,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1557878.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:对象   映射器

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!