首页 > 解决方案 > 带有“new”修饰符的 AutoMapper 继承

问题描述

我正在将我的项目从 AutoMapper 版本 4.2.1 更新到 6,在新版本中,我得到了一个意外的行为。

课程

class Opportunity : OpportunityLite
{
}

class OpportunityLite
{
    public DealerOpportunityLite DealerOpportunity { get; set; }
}

class DealerOpportunity : DealerOpportunityLite
{
    public new string BranchCode { get; set; }
}

class DealerOpportunityLite
{
    public string BranchCode { get; set; }
}

映射器配置

AutoMapper.Mapper.Initialize(cfg =>
{
    cfg.CreateMap<Opportunity, OpportunityLite>();
    cfg.CreateMap<DealerOpportunity, DealerOpportunityLite>();
});

版本:4.2.1

如果我执行以下地图:

Opportunity oppLite = new Opportunity
{
    DealerOpportunity = new DealerOpportunity
    {
        BranchCode = "00168"
    }
};

var opp = AutoMapper.Mapper.Map<Opportunity, OpportunityLite>(oppLite);

“opp.DealerOpportunity.BranchCode”的属性值为:00168

从版本 5.0.2 到 6.2.2

在这些版本中,相同属性的值是:null

如何更新 AutoMapper 以获得与 4.2.1 版相同的结果,而无需在映射配置中添加“ForMember”?不幸的是,我有很多此类模式的案例。

标签: c#inheritanceautomapperautomapper-5automapper-4

解决方案


推荐阅读