inheritance - 来自基类的 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;
}
解决方案
推荐阅读
- c++ - 带有 2d 向量的 C++ 中的分段错误(核心转储)
- sql-server - 尝试访问 Docker 上的 SQL Server 时,在建立与 SQL Server 的连接时发生网络相关或特定于实例的错误
- reactjs - 条形图中的标签?
- hadoop - 计算一系列日期之间的日期字符串
- java - jooq 使用 mapInto 从多个表中选择
- angular - 无法使用角材料中的 mat-tab-nav-bar 覆盖 mat-ink-bar 颜色
- python - 导入库的问题
- r - 构建函数以将自然中断jenks应用于我的df列时出错
- javascript - 通过 URL 参数设置 cookie 并在整个网站上保持其值
- excel - EXCEL VBA 运行时错误 91 - 未设置对象