【问题标题】:Automapper: Retrieve DTO mappingAutomapper:检索 DTO 映射
【发布时间】:2014-08-26 20:41:00
【问题描述】:

假设我已注册 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”。 我在这里错过了什么?

【问题讨论】:

    标签: c# automapper


    【解决方案1】:

    您不能将泛型类型参数作为运行时参数传递,它们需要在编译时设置。您的代码没有将类型参数设置为 sourceType 变量中的值,它告诉编译器该类型称为 sourceType,因此您会收到编译错误,因为您尚未定义称为 sourceType 的类型。

    【讨论】:

    • 我明白了,所以我无法映射到这个未知的 DTO 吗?也许有反思?
    • 您的根本问题是您无法在运行时设置泛型类型参数。您可以使用反射映射到要在运行时决定的类型,但仍然存在无法设置SaveServiceRequest 的泛型类型参数的问题。
    猜你喜欢
    • 2016-04-13
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多