自动映射器 UseDestinationValue

5

遇到了映射问题

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);
1个回答

8

我从未使用过UseDestinationValue()选项,但是看起来你只是想在从VPerson到DPerson的映射中不映射Id。如果是这样,请使用Ignore选项:

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

编辑

糟糕——我甚至没有注意到你使用的语法。你需要使用接受现有目标对象的“Map”重载:

Mapper.Map(vPerson, dPerson);

您使用的版本会创建一个新的DPerson,然后执行映射。而我上面展示的版本则是取已经创建好的dPerson,然后执行映射(并且使用上面展示的Ignore选项,您的Id不会被覆盖)。

如果我使用这个选项,我会得到相同的结果。 - mimo
2
现在它使用UseDestinationValue工作了,非常感谢您的帮助 :-) - mimo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接