Joe Defill
Joe Defill

Reputation: 499

AutoMapper - mapping integers to int array

I'm trying to map integers from a database to an int array, but I'm getting the error: AutoMapper.AutoMapperConfigurationException: 'Custom configuration for members is only supported for top level individual members on a type.'

This is what I have:

Model:

public class Year
{
    public int[] Months { get; set; } = new int[3];
}

Mapping:

CreateMap<DataRow, Year>()
    .ForMember(dest => dest.Months[0], opt => opt.MapFrom(src => src["Jan"]))
    .ForMember(dest => dest.Months[1], opt => opt.MapFrom(src => src["Feb"]))
    .ForMember(dest => dest.Months[2], opt => opt.MapFrom(src => src["Mar"]))

Anyone know how to get this to work?

Upvotes: 0

Views: 781

Answers (1)

Kit
Kit

Reputation: 21739

You will need to do something like this

.ForMember(dest => dest.Months, opt => opt.MapFrom(src => MapFromRow(src)))

where you have a method

int[] MapFromRow(DataRow src)
{
    int months = new int[12];

    months[0] = src["Jan"];
    ...
    return months;
}

AutoMapper does not seem to support "dotting" into a property or indexing into an array.

If you want to go fully inline, you can do

.ForMember(dest => dest.Months, opt => opt.MapFrom(src => new int[]
    {
        (int)src["Jan"], (int)src["Feb"], ...
    }))

Upvotes: 3

Related Questions