7

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:

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

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>>

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.

Any ideas?

TaniaMaria
  • 83
  • 1
  • 3
  • I've simplified it down and have run some unit tests, and unfortunately it doesn't look like IGrouping is currently supported. If you get no resolution from here, you could also try the [AutoMapper Mailing List](https://groups.google.com/forum/?fromgroups#!forum/automapper-users) – Mightymuke Nov 09 '12 at 11:17

1 Answers1

7

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

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

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 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.

Prasad Kanaparthi
  • 6,423
  • 4
  • 35
  • 62
  • 1
    @TaniaMaria, Did you tried with this approach? Please let me know. – Prasad Kanaparthi Nov 09 '12 at 14:22
  • 1
    I believe IGrouping is now supported. I'm able to successfully map from IGrouping to entityDto; and automapper automatically supports List<> to List<> mappings if the individual mappings are configured – Daniel Brown Oct 02 '16 at 00:23