首页 > 解决方案 > 来自基类的 AutoMapper 映射包括派生类

问题描述

需要一些关于我试图解决的 Automapper 问题的专家建议。

我有三个类,一个实体、一个基类和一个派生类。

public class MyEntity
{
   public string RefNumber {get;set;}
}

public class MyBaseClass
{
    public string UserName {get;set;}
}

public class MyDto : MyBaseClass
{
    public string RefNumber {get;set;}
}

public class MyDto2 : MyBaseClass
{
    public string InvoiceNumber {get;set;}
}  

基于 Automapper 文档,我创建了以下映射

CreateMap<MyEntity, MyBaseClass>()
           .ForPath(d => d.UserName , opt => opt.MapFrom(src => src.UserName))
           .IncludeAllDerived();

CreateMap<MyEntity, MyDto>()
           .ForMember(d => d.RefNumber, opt => opt.MapFrom(src => src.RefNumber));

此时我可以轻松地映射 MyDto 或 MyBaseClass:

       var entity = GetEntity();

       var myMappedDto = _mapper.Map<MyDto>(entity);

       var myMappedBase = _mapper.Map<MyBaseClass>(entity);

myMappedDto 和 myMappedBase 都返回了我所期望的结果,但是,这里真正的要求是映射实体相关的 Dto(MyDto、MyDto2 等)并返回来自 MyBaseClass 的道具。

希望这是有道理的......欣赏输入。

 public async Task<MyBaseClass> GetAsync(int id)
    {
        var entity = await GetEntity(jobId);

        //based on entity programatically choose the related Dto and map that 
        var mappedThing = _mapper.Map<MyDto>(entity);

        //OR map the base class and somehow magically include the relevant DTO props
        var mappedThing = _mapper.Map<MyBaseClass>(entity);

        return mappedThing;
    }

标签: inheritanceautomapperautomapper-6

解决方案


推荐阅读