c# – Automapper 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,或者我错过了什么?

工作实例

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.如果是这种情况,请使用“忽略”选项:

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

编辑

哦拍 – 我甚至没有注意到你使用的语法.您需要使用接受现有目标对象的“Map”重载:

Mapper.Map(vPerson, dPerson);

您正在使用的版本创建一个新的DPerson,然后执行映射.我上面展示的那个使用已经创建的dPerson然后执行映射(并且使用上面显示的Ignore选项,您的Id不会被覆盖).

上一篇:c# – Automapper:如何映射嵌套对象?


下一篇:c# – Automapper:将JSON转换为对象列表