使用Automapper如何将IEnumerable<something>转换为IEnumerable<somethingelse>而不创建映射配置?

9
我无法让下面的代码正常运行,其中array是一个CustomerContract数组:
Mapper.Map<IEnumerable<Customer>>(array);

Mapper.Map<IEnumerable<CustomerContract>, IEnumerable<Customer>>(array);

Mapper.Map<Array, List<Customer>>(array);

在我的想法中,第一个示例应该足够了,但我无法使它们都起作用。我已经阅读了Automapper的配置wiki(https://github.com/AutoMapper/AutoMapper/wiki/Configuration),但我不明白为什么这是必要的。 Automapper需要的一切都在命令中定义。它是哪种类型(对象和列表),以及我想将其映射到哪个对象。

我是否没有理解Automapper的核心概念?

我的异常信息如下:

缺少类型映射配置或不支持映射。
映射类型:\r\nCustomerContract -> Customer\r\nStimline.Xplorer.Repository.CustomerService.CustomerContract -> Stimline.Xplorer.BusinessObjects.Customer
目标路径:List`1[0]
源值:Stimline.Xplorer.Repository.CustomerService.CustomerContract

1个回答

17

你正在映射到IEnumerable... Automapper可以映射到具体类型而不是接口。

首先注册您的映射(参见“缺少类型映射配置或不支持的映射”)。 为了提高性能,您必须使用CreateMap。

Mapper.CreateMap<something, somethingelse>();

改为:

Mapper.Map<IEnumerable<Customer>>(array);

试试这个:

Mapper.Map<List<Customer>>(array);
或者
Mapper.Map<Customer[]>(array);

谢谢,它起作用了。但我仍然不明白为什么需要创建地图...它应该能够从Mapper.Map<List<Customer>>(array)的输入中确定CreateMap提供的所有信息...为什么不能呢? - Bjørn
2
@Swell,我的理解是autoMapper支持所有通用集合类型。具体来说,这里是列表:IEnumerable,IEnumerable<T>,ICollection,ICollection<T>,IList,IList<T>,List<T>,Arrays。 - Bayeni
1
@BjørnØyvindHalvorsen 因为CreateMap实际上是一个缓慢的方法... 如果每次调用Map都调用CreateMap,它会影响应用程序的性能。 - JuChom
@Bayeni 是的,但是当您将IEnumerable<T>作为目标时,Automapper应该返回什么?Collection<T>? List<T>? - JuChom
1
它将返回IEnumerable<DestinationType>,即IEnumerable<DestinationType> ienumerableDest = Mapper.Map<SourceType[], IEnumerable<DestinationType>>(sources); 谢谢Swell。 - Bayeni

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接