自动映射器:部分映射 [英] Automapper : partial mapping
问题描述
我正在使用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 ,谢谢您的帮助
这篇关于自动映射器:部分映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!