4

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

1 Answer 1

6

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]
}
Sign up to request clarification or add additional context in comments.

3 Comments

@Dror Helper yes, see my last update with quote from automapper wiki.
Yes - but there are tricks such as custom converters and other facilities perhaps one of them would help
@Dror Helper, yes you can write type converter, or use lambda like in my last sample. But it's not much simpler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.