簡體   English   中英

自動映射器:檢索DTO映射

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM