Automapper UseDestinationValue

喜欢而已 提交于 2021-02-07 18:19:20

问题


Having a problem with a mapping

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 is 0, I would think it should be 1, or am I missing something?

Working example

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);

回答1:


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());

EDIT

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);

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).



来源:https://stackoverflow.com/questions/5243762/automapper-usedestinationvalue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!