【问题标题】:Automapper exception : must resolve to top-level memberAutomapper 异常:必须解析为顶级成员
【发布时间】:2021-08-06 17:33:32
【问题描述】:

如何将以下 ItemId(作为源)与 DataId(作为输出)映射:

来源:

public class Source
{
    public InputData InputItem { get; set; }
}
public class InputData
{
    public int ItemID { get; set; }
}

输出:

public class Output
{
    public List<OutputData> OutputItem { get; set; }
}
public class OutputData
{
    public string[] DataID { get; set; }
}

我正在尝试通过以下方式对其进行映射:

CreateMap<Source, Output>().ForMember(d => d.OutputItem[0].DataID,
   option => option.MapFrom(s => s.InputItem != null ? new string[] { $"item_{s.InputItem.ItemID}" } : null));

获取异常:

Expression 'd => d.OutputItem.get_Item(0).DataID' 必须解析为顶级成员,而不是任何子对象的属性。在子类型或 AfterMap 选项上使用自定义解析器。参数名称:lambdaExpression

谁能帮我映射这些对象。

谢谢

【问题讨论】:

  • 可以,但也不能使用 CustomTypeConverter。

标签: c# automapper


【解决方案1】:

该错误基本上表明您只能为对象的一个​​级别定义映射。您不能将映射定义为直接写入子对象的属性。

通过为每个级别的对象定义单独的映射来解决这个问题。

首先定义子对象的映射:

CreateMap<InputData, OutputData>().ForMember(d => d.DataID,
       option => option.MapFrom(s => s != null ? new string[] { $"item_{s.ItemID}" } : null));

然后父对象的映射可以使用这个定义来映射它的子对象。 (像List&lt;OutputData&gt;这样的集合应该由AutoMapper自动填充。)

CreateMap<Source, Output>().ForMember(d => d.OutputItem,
       option => option.MapFrom(s => s.InputItem));

【讨论】:

  • OP 在 List&lt;OutputData&gt; 内有 Output 。这仍然会报错 Missing type map configuration or unsupported mapping between InputData and List&lt;OutputData&gt;
  • 我没有尝试上面给出的映射,但据我所知,如果 automapper 知道如何映射集合中包含的对象,它应该自动将项目添加到列表中。
  • 如果源和目标都是集合,它将起作用。但是我怀疑在这种特殊情况下。
  • @GeorgPatscheider 出现以下异常:缺少类型映射配置或不支持映射。 映射类型:Char -> OutputData System.Char -> Models.OutputData
  • 这是堆栈跟踪at lambda_method(Closure , Char , OutputData, ResolutionContext ) at lambda_method(Closure , Object , Output , ResolutionContext )
猜你喜欢
  • 2012-07-22
  • 2018-08-06
  • 1970-01-01
  • 1970-01-01
  • 2015-01-30
  • 2020-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多