Inheritance 来自基类的自动映射包括派生类

Inheritance 来自基类的自动映射包括派生类,inheritance,automapper,automapper-6,Inheritance,Automapper,Automapper 6,我需要一些专家的建议来解决这个汽车制造商的问题 我有三个类,一个实体、一个基类和一个派生类 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 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));
CreateMap()
.ForPath(d=>d.UserName,opt=>opt.MapFrom(src=>src.UserName))
.includealderived();
CreateMap()
.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);
var entity=GetEntity();
var myMappedDto=\u mapper.Map(实体);
var myMappedBase=\u mapper.Map(实体);
MyMappedTo和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;
    }
公共异步任务GetAsync(int-id) { var实体=等待获取实体(jobId); //基于实体,通过编程选择相关的Dto并映射 var mappedThing=_mapper.Map(实体); //或者映射基类并以某种方式神奇地包含相关的DTO道具 var mappedThing=_mapper.Map(实体); 返回映射对象; }
谢谢,我使用这些文档创建了我目前拥有的文档。这些文档解释说,当映射到基类型时,派生类型由源类型选择。但是您只有一种源类型,所以AM不能为您这样做。因此,您必须以某种方式选择目的地类型。关于这一点有很多问题,也有一些方法。