自动映射器:部分映射

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

我正在使用Automapper将数据从objectA传输到objectB

I am using Automapper to transfer data from objectA to objectB

classe ObjectA { string Title; string Summary; } classe ObjectB { string Title; string Summary; IAddress Address; }

我在两个对象之间创建了这种映射

I created this kind of mapping between the two objects

AutoMapper.Mapper.CreateMap<IObectA, IObjectB>() .ForMember(dest => dest.Title, src => src.MapFrom(s => s.Title)) .ForMember(dest => dest.Summary, src => src.MapFrom(s => s.Summary)) .ForMember(dest => dest.Address, src => src.Ignore())

我创建我的ObjectB并填充其所有属性,包括地址

I create my ObjectB and fill all its properties including Address

当我调用映射器时,我期望它会覆盖标题"和摘要",而忽略地址"

When I call the mapper, I was expecting it to override Title and Summary and ignore Address

ObjectB = Mapper.Map<IObjectA, IObjectB>(objectA);

实际上,它是对Address的抛出和异常.

Actually, it is throwing and exception for Address.

我做错了什么?

[UPDATE] 为了表达不同,我有我的objectB,我想用来自ObjectA的数据更新它的一部分.当我说忽略"时,我的意思是将数据保留为原来的状态

[UPDATE] To express it differently, I have my objectB and I want to update part of it with data coming from ObjectA. When I say Ignore, I mean leave the data the way they already are

推荐答案

我找到了解决方案.

我刚刚发现Map方法具有一个重载版本,除了预先实例化的目标对象外. 感谢此文章

I just discovered that Map method has an overloaded version that excepts a pre-instantiated destination object. Thanks to this article

Mapper.Map<IObjectA, IObjectB>(objectA, ObjectB );

@JoDG ,谢谢您的帮助

更多推荐

自动映射器:部分映射

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

发布评论

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

>www.elefans.com

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