简体   繁体   English

AutoMapper - Map 子属性隐藏库 class 属性

[英]AutoMapper - Map child property hiding base class property

I'm encountering a quite stupid issue while trying to map a class to a derived class using AutoMapper with C#.我在尝试使用带有 C# 的AutoMapper将 map a class 派生为 class 时遇到了一个非常愚蠢的问题。

These are my classes:这些是我的课程:

class BaseParent {
    public string Name { get; set; }
    public BaseChild Child { get; set; }
}

class BaseChild {
    public int Age { get; set; }
}

class DerivedParent : BaseParent {
    public new DerivedChild Child { get; set; }
}

class DerivedChild : BaseChild { }

In particular, what I'm trying to achieve is that all the properties of the mapped class are correctly set.特别是,我要实现的是正确设置映射的 class 的所有属性。 The issue is that the Child property of the mapped class is not set and remains null .问题是映射的 class 的Child属性未设置并保持为 null

This is the mapping configuration I'm using:这是我正在使用的映射配置:

var config = new MapperConfiguration(cfg => {
        cfg.CreateMap<BaseChild, DerivedChild>();
        cfg.CreateMap<BaseParent, DerivedParent>()
            .ForMember(dest => dest.Child, opt => opt.MapFrom(src => src.Child));
    });

Any help is appreciated.任何帮助表示赞赏。

Thanks谢谢

EDIT编辑

Actually is not correct to say that Child property remains null .实际上说Child属性仍然是null是不正确的。 Debugging the code I can see that there are 2 child properties with the same name because of the new modifier used to hide the parent one.调试代码我可以看到有 2 个子属性具有相同的名称,因为用于隐藏父属性的new修饰符。

Anyway, the property I need is still null .不管怎样,我需要的财产仍然是null

Are you sure you're looking at it correctly?你确定你看对了吗?

Given the following config:给定以下配置:

// Arrange
var mapper = new Mapper(new MapperConfiguration(cfg => {
    cfg.CreateMap<BaseChild, DerivedChild>();
    cfg.CreateMap<BaseParent, DerivedParent>()
        .ForMember(dest => dest.Child, opt => opt.MapFrom(src => src.Child));
}));
var baseParent = new BaseParent { Name = "A", Child = new BaseChild { Age = 1 } };

// Act
var derived = mapper.Map<DerivedParent>(baseParent);

I can assure you that:我可以向你保证:

  • derived.Child is certainly not null derived.Child肯定not null
  • It is of type DerivedChild它是DerivedChild类型
  • The hidden BaseChild is null隐藏的BaseChildnull

Which you can see in the following ( see working Fiddle ):您可以在以下内容中看到(请参阅 working Fiddle ):

// Assert
Assert.IsNotNull(derived);
Assert.IsInstanceOf<DerivedParent>(derived);

// The 'new' Child property is not null
Assert.IsNotNull(derived.Child);
Assert.IsInstanceOf<DerivedChild>(derived.Child);

// The hidden property should be null
Assert.IsNull(((BaseParent)derived).Child);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM