自动映射器UseDestinationValue

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

映射有问题

VPerson vPerson = new VPerson() { Id = 2, Lastname = "Hansen1", Name = "Morten1" }; DPerson dPerson = new DPerson() { Id = 1, Lastname = "Hansen", Name = "Morten" }; Mapper.Initialize(x => { //x.AllowNullDestinationValues = true; // does exactly what it says (false by default) }); Mapper.CreateMap(); Mapper.CreateMap() .ForMember(dest => dest.Id, opt => opt.UseDestinationValue()); Mapper.AssertConfigurationIsValid(); dPerson = Mapper.Map<VPerson, DPerson>(vPerson);

dPerson 为0,我认为应该为1,还是我遗漏了什么?

dPerson is 0, I would think it should be 1, or am I missing something?

工作示例

VPerson vPerson = new VPerson() { Id = 2, Lastname = "Hansen1", Name = "Morten1" }; DPerson dPerson = new DPerson() { Id = 1, Lastname = "Hansen", Name = "Morten" }; Mapper.Initialize(x => { //x.AllowNullDestinationValues = true; // does exactly what it says (false by default) }); Mapper.CreateMap<DPerson, VPerson>(); Mapper.CreateMap<VPerson, DPerson>() .ForMember(dest => dest.Id, opt => opt.UseDestinationValue()); Mapper.AssertConfigurationIsValid(); dPerson = Mapper.Map(vPerson, dPerson);

推荐答案

从不使用UseDestinationValue()选项,但是看起来您只是想从VPerson到DPerson时不映射ID.如果是这种情况,请使用忽略"选项:

Never used the UseDestinationValue() option, but it looks like you just want to NOT map the Id when going from VPerson to DPerson. If that is the case, use the Ignore option:

.ForMember(d => d.Id, o => o.Ignore());

编辑

哦,开枪-我什至没有注意到您使用的语法.您需要使用接受现有目标对象的地图"重载:

Oh shoot -- I didn't even notice the syntax you were using. You need to use the overload of "Map" that accepts the existing destination object:

Mapper.Map(vPerson, dPerson);

您使用的版本会创建一个新的DPerson,然后执行映射.我在上面显示的代码使用了已经创建的dPerson,然后执行了映射(使用上面显示的忽略"选项,您的ID不会被覆盖).

The version you're using creates a new DPerson and then performs the mappings. The one I show above takes the already-created dPerson and then performs the mappings (and with the Ignore option shown above, your Id is not overwritten).

更多推荐

自动映射器UseDestinationValue

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

发布评论

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

>www.elefans.com

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