使用映射一个AutoMapper分组集合 [英] Mapping a grouped collection using AutoMapper

查看:1061
本文介绍了使用映射一个AutoMapper分组集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码,这是行不通的:

I have the following code which is not working:

var groupedZones = this._zoneDataManager.GetZonesGroupedByCountry();
            IEnumerable<IGrouping<String, ZoneDTO>> zonesToReturn = Mapper.Map<IEnumerable<IGrouping<String, Zone>>, IEnumerable<IGrouping<String, ZoneDTO>>>(groupedZones);



我不断收到以下异常:

I keep getting the following exception:

价值
\System.Collections.Generic.List 1 [SCGRE.Business.Model.ZoneDTO] \是
不是型
\System.Linq.IGrouping
2 [System.String,SCGRE.Business.Model.ZoneDTO] \
和不能这个通用集合中的使用。 \r\\\
Parameter名:

The value \"System.Collections.Generic.List1[SCGRE.Business.Model.ZoneDTO]\" is not of type \"System.Linq.IGrouping2[System.String,SCGRE.Business.Model.ZoneDTO]\" and cannot be used in this generic collection.\r\nParameter name: value

我不明白为什么它正试图映射列表< T> IGrouping<弦乐,T> 或也许我没有正确理解例外...但是我基本上有一个的IEnumerable< IGrouping<弦乐,区>> ,我想它映射到的IEnumerable< IGrouping<弦乐,ZoneDTO>>

I do not understand why it is trying to map a List<T> into an IGrouping<String, T> or maybe I did not understand the exception properly... But I basically have an IEnumerable<IGrouping<String, Zone>> and I want to map it to IEnumerable<IGrouping<String, ZoneDTO>>

这是我创建了一个地图从 ZoneDTO注如下:

Note that I have created a map from Zone to ZoneDTO as follows:

Mapper.CreateMap<Zone, ZoneDTO>();



这是因为这两个类几乎完全一样的属性。

And that's because both classes have almost exactly the same properties.

任何想法?

推荐答案

在一些工作以防万一,我想你不能做某些事情像

After some work arround, I guess you cannot do some thing like

 Mapper.CreateMap<IEnumerable<IGrouping<String, Zone>>, IEnumerable<IGrouping<String, ZoneDTO>>>()

要具体,AutoMapper支持源集合类型包括:(仅通用类型)

To be specific, AutoMapper supports the source collection types include: (Only Generic types)

IEnumerable, IEnumerable<T>, ICollection, ICollection<T>, IList, IList<T>, List<T>, Arrays

AutoMapper将不支持 IGrouping ,因为它不通用枚举类型。

AutoMapper will not support IGrouping because it is non-generic enumerable type.

相反,你可以做以下简单的办法,

Instead you can do the following simple approach,

var zones = this._zoneDataManager.GetZones();   // Write new method in your ZoneDataManager
var zoneDTOs = Mapper.Map<List<Zone>, List<ZoneDTO>>(zones);
IEnumerable<IGrouping<String, ZoneDTO>> zonesToReturn = zoneDTOs.GroupBy(z => z.Country); 

请阅读的这个。希望这有助于。

Please read this. Hope this helps.

这篇关于使用映射一个AutoMapper分组集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆