简体   繁体   English

自动映射器:检索DTO映射

[英]Automapper: Retrieve DTO mapping

Assuming I have registered DTO's (which implement IBaseDto) to map to entities (which implement IUpdateEntity) 假设我已经注册了DTO(实现IBaseDto)以映射到实体(实现IUpdateEntity)

Now when I have a generic TEntity (currentItem), I want to find the correct DTO type it is mapped to. 现在,当我有一个通用的TEntity(currentItem)时,我想找到它映射到的正确的DTO类型。 I have the following code: 我有以下代码:

  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
  }

Now the problem I'm having is on the line where I try to map the currentItem to a DTO. 现在我遇到的问题是我尝试将currentItem映射到DTO的那一行。 VS/Resharper says It cannot resolve the symbol "sourceType". VS / Resharper说,它无法解析符号“ sourceType”。 What am I missing here? 我在这里想念什么?

You cannot pass generic type parameters as runtime arguments they need to be set at compile time. 您不能将泛型类型参数作为运行时参数传递,而需要在编译时进行设置。 Your code does not set the type parameter to the value in the sourceType variable, it is telling the compiler that the type is called sourceType so you are getting a compilation error as you have not defined a type called sourceType. 您的代码未将type参数设置为sourceType变量中的值,它是告诉编译器该类型称为sourceType,因此由于未定义一个名为sourceType的类型,因此您会遇到编译错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM