[英]Automapper: Retrieve DTO mapping
假设我已经注册了DTO(实现IBaseDto)以映射到实体(实现IUpdateEntity)
现在,当我有一个通用的TEntity(currentItem)时,我想找到它映射到的正确的DTO类型。 我有以下代码:
var mappings = Mapper.GetAllTypeMaps();
var typeMap = mappings.FirstOrDefault(m => m.DestinationType == typeof (TEntity) && m.SourceType == typeof(BaseDto));
if (typeMap != null)
{
var sourceType = typeMap.SourceType;
var dto = currentItem.Map().To<sourceType>(); //map the entity to it's DTO
var request = new SaveServiceRequest<sourceType> { Entity = currentItem }; // create a SaveServiceRequest
SaveItem(request); //save the DTO
}
现在我遇到的问题是我尝试将currentItem映射到DTO的那一行。 VS / Resharper说,它无法解析符号“ sourceType”。 我在这里想念什么?
您不能将泛型类型参数作为运行时参数传递,而需要在编译时进行设置。 您的代码未将type参数设置为sourceType
变量中的值,它是告诉编译器该类型称为sourceType,因此由于未定义一个名为sourceType的类型,因此您会遇到编译错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.