英文:
Automapper - Map fail from class to list
问题
I got the following mapping:
- 将类A映射到List<B>
- 将类B映射到类C
所以,这是代码片段:
// 从类A映射到IEnumerable<B>
cfg.CreateMap<A, IEnumerable<B>>().ConvertUsing((i, o) => i.listB);
// 从类B映射到类C
cfg.CreateMap<B, C>();
var listB = mapper.Map<A, IEnumerable<B>>(instanceA); // 可行
var instanceC = mapper.Map<B, C>(listB.First()); // 可行
var listC = mapper.Map<IEnumerable<B>, IEnumerable<C>>(listB); // 可行
var listCFail = mapper.Map<A, IEnumerable<C>>(instanceA); // 引发以下异常:缺少类型映射配置或不支持的映射。
我认为这种用例(从类A到IEnumerable<C>)应该可行,我错过了什么?
非常感谢
英文:
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<B>
cfg.CreateMap<A, IEnumerable<B>>().ConvertUsing((i, o) => i.listB);
// Mapping from class B to class C
cfg.CreateMap<B, C>();
var listB = mapper.Map<A, IEnumerable<B>>(instanceA); // Works
var instanceC = mapper.Map<B, C>(listB.First()); // Works
var listC = mapper.Map<IEnumerable<B>, IEnumerable<C>>(listB); // Works
var listCFail = mapper.Map<A, IEnumerable<C>>(instanceA); // Throw the following exception: Missing type map configuration or unsupported mapping.'
I thought this use case (class A to IEnumerable<C>) should works, what did I missed ?
Thanks a lot
答案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<B>
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 => a.listB.Select(b => mapper.Map<B, C>(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<B>
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<A, IEnumerable<C>>()
.ConvertUsing(a => a.listB.Select(b => mapper.Map<B, C>(b)));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论