How to map an array to multiple properties using AutoMapper?

I need to map a single fixed sized array array to multiple properties. For example given this class:

public class Source
{
    public int[] ItemArray{get;set} // always 4 items
}

I want to map the array to this class

public class Dest
{
    public int Item1 { get; set; }
    public int Item2 { get; set; }
    public int Item3 { get; set; }
    public int Item4 { get; set; }
}

Is there a simple way to do it with AutoMapper (without actually mapping each individual field)?

Answer

Create mappings for properties of Dest:

Mapper.CreateMap<Source, Dest>()
    .ForMember(d => d.Item1, o => o.MapFrom(s => s.ItemArray[0]))
    .ForMember(d => d.Item2, o => o.MapFrom(s => s.ItemArray[1]))
    .ForMember(d => d.Item3, o => o.MapFrom(s => s.ItemArray[2]))
    .ForMember(d => d.Item4, o => o.MapFrom(s => s.ItemArray[3]));

Usage:

Source source = new Source() { ItemArray = new int[] { 1, 2, 3, 4 } };
Dest dest = Mapper.Map<Source, Dest>(source);

UPDATE: No, there is no simple way. How AutoMapper will understand, that your property Foo should be mapped to element at index N in source property Bar? You should provide all this info.

UPDATE: From Automapper

Projection transforms a source to a destination beyond flattening the object model. Without extra configuration, AutoMapper requires a flattened destination to match the source type’s naming structure. When you want to project source values into a destination that does not exactly match the source structure, you must specify custom member mapping definitions.

So, yes. If naming structure does not match, you must specify custom mapping for members.

UPDATE: Well, actually you can do all conversion manually (but I don’t think it’s much better way, especially if you have other properties which could be mapped by name):

Mapper.CreateMap<Source, Dest>().ConstructUsing((s) => new Dest()
{
    Item1 = s.ItemArray[0],
    Item2 = s.ItemArray[1],
    Item3 = s.ItemArray[2],
    Item4 = s.ItemArray[3]
}

Leave a Reply

Your email address will not be published. Required fields are marked *