Automapper – 从类映射到列表失败

huangapple go评论67阅读模式
英文:

Automapper - Map fail from class to list

问题

I got the following mapping:

  • 将类A映射到List<B>
  • 将类B映射到类C

所以,这是代码片段:

// 从类A映射到IEnumerable&lt;B&gt;
cfg.CreateMap&lt;A, IEnumerable&lt;B&gt;&gt;().ConvertUsing((i, o) =&gt; i.listB);
// 从类B映射到类C
cfg.CreateMap&lt;B, C&gt;();

var listB = mapper.Map&lt;A, IEnumerable&lt;B&gt;&gt;(instanceA); // 可行
var instanceC = mapper.Map&lt;B, C&gt;(listB.First()); // 可行
var listC = mapper.Map&lt;IEnumerable&lt;B&gt;, IEnumerable&lt;C&gt;&gt;(listB); // 可行

var listCFail = mapper.Map&lt;A, IEnumerable&lt;C&gt;&gt;(instanceA); // 引发以下异常:缺少类型映射配置或不支持的映射。

我认为这种用例(从类A到IEnumerable<C>)应该可行,我错过了什么?
非常感谢 Automapper – 从类映射到列表失败

英文:

I got the following mapping :

  • Class A to List<B>
  • Class B to class C

So, here is the snippet:

// Mapping from class A to IEnumerable&lt;B&gt;
cfg.CreateMap&lt;A, IEnumerable&lt;B&gt;&gt;().ConvertUsing((i, o) =&gt; i.listB);
// Mapping from class B to class C
cfg.CreateMap&lt;B, C&gt;();

var listB = mapper.Map&lt;A, IEnumerable&lt;B&gt;&gt;(instanceA); // Works
var instanceC = mapper.Map&lt;B, C&gt;(listB.First()); // Works
var listC = mapper.Map&lt;IEnumerable&lt;B&gt;, IEnumerable&lt;C&gt;&gt;(listB); // Works

var listCFail = mapper.Map&lt;A, IEnumerable&lt;C&gt;&gt;(instanceA); // Throw the following exception: Missing type map configuration or unsupported mapping.&#39;

I thought this use case (class A to IEnumerable<C>) should works, what did I missed ?
Thanks a lot Automapper – 从类映射到列表失败

答案1

得分: 1

I agree with the comment:

> No transitivity I'm afraid, that's what the message is telling you and you''ll have to add the missing map. –
Lucian Bargaoan

Even though there are mappings from A to IEnumerable&lt;B&gt; and B to class C, it is not enough for AutoMapper to understand how should the "derived" mapping work. It needs to know the mapping explicitly:

    .ConvertUsing(a =&gt; a.listB.Select(b =&gt; mapper.Map&lt;B, C&gt;(b)));
英文:

I agree with the comment:

> No transitivity I'm afraid, that's what the message is telling you and you''ll have to add the missing map. –
Lucian Bargaoan

Even though there are mappings from A to IEnumerable&lt;B&gt; and B to class C, it is not enough for AutoMapper to understand how should the "derived" mapping work. It needs to know the mapping explicitly:

cfg.CreateMap&lt;A, IEnumerable&lt;C&gt;&gt;()
    .ConvertUsing(a =&gt; a.listB.Select(b =&gt; mapper.Map&lt;B, C&gt;(b)));

huangapple
  • 本文由 发表于 2023年2月27日 03:21:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75574458.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定