自动将一个源映射到多个目标

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

下面是我的课程

class Dest1 { string prop1; string prop2; strig prop3; public Dest2 Dest2 {get;set;} pubic List<Dest3> Dest3 {get;set;} } class Dest2 { string prop4; string prop5; strig prop6; } class Dest3 { string prop7; } class Source1 { string prop1; string prop2; string prop3; string prop4; } class Source2 { string prop7; }

我需要地图

Q1.从source1类到Dest1类(我也需要映射dest2对象)

Q1. source1 class to Dest1 Class( also i need to map dest2 object)

Q2.我需要将Dest1映射回源1(反向映射)

Q2. I need to do map Dest1 back to Source 1 (reverse map)

Am使用核心和自动映射器.对于automapper& 核心..提前感谢

Am using core and auto mapper.. am new to automapper & core ..Thanks in advance

推荐答案

如果您配置了映射,则AutoMapper可以从多个源映射到任意多个目的地.例如,您请求的方案:

AutoMapper can map from as many sources to as many destinations as you would like, assuming you configure the mapping. For example, your requested scenario:

var configuration = new MapperConfiguration(cfg => // Mapping Config cfg.CreateMap<Source1, Dest2>() .ForMember(dest => dest.prop5, opt => opt.Ignore()) .ForMember(dest => dest.prop6, opt => opt.Ignore()); cfg.CreateMap<Source1, Dest1>() .ForMember(dest => dest.Dest2, opt => opt.MapFrom(src => src)); // Reverse Mapping Config cfg.CreateMap<Dest1, Source1>() .ForMember(dest => dest.prop4, opt => opt.MapFrom(src => (src?.Dest2 != null) // ?. w/c#6 ? src.Dest2.prop4 // map if can : null)); // otherwise null ); // Check AutoMapper configuration configuration.AssertConfigurationIsValid();

具有相同名称的属性将自动映射.任何没有相应来源属性的目标属性都将被忽略.

Properties with the same name will map automatically. Any destination properties that don’t have a corresponding source property will need to be ignored.

一旦配置了AutoMapper,就可以使用IMapper界面根据需要进行映射.

Once your AutoMapper is configured, you can map as needed with the use of the IMapper interface.

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

更多推荐

自动将一个源映射到多个目标

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

发布评论

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

>www.elefans.com

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