Martin
Martin

Reputation: 24308

automapper: Mapping from an array to one field?

I am having an issue trying to map an array to a type. I get the following error

Missing type map configuration or unsupported mapping.

Mapping types:
Run[] -> Run

The destination item is a Run and the source is a Run (array of).... I setup my mappings in global.asax

   Mapper.CreateMap<Model.Run, Run>();

Any ideas, I think I am missing something.

Upvotes: 1

Views: 4305

Answers (1)

Patryk Ćwiek
Patryk Ćwiek

Reputation: 14318

AutoMapper can automatically map collection-to-collection when you have specified the type mapping, so when you have:

Mapper.CreateMap<Model.Run, Run>();

you can just go with

var runs = Mapper.Map<IEnumerable<Model.Run>, IEnumerable<Run>>(source);

because it follows naturally - it maps every item of the source collection to destination collection using the one-to-one map you have specified. What doesn't follow is automatic T -> T[] or T[] -> T mapping, what should the mapper do when you map T[] -> T? Take the first item from array? Or maybe the last one? Do some kind of aggregation? What if the collection is empty?

You have to write a separate, full map for that, e.g:

Mapper.CreateMap<Model.Run[], Run>()
      .ForMember(x => x.NumericMember, expr => expr.MapFrom(y => y.Sum(z => z.NumericMember)))
      .ForMember(//etc...);

Upvotes: 6

Related Questions