AutoMapper-将整数映射到int数组

时间:2018-12-31 20:26:37

标签: c# automapper

我正在尝试将整数从数据库映射到int数组,但出现错误:AutoMapper.AutoMapperConfigurationException: 'Custom configuration for members is only supported for top level individual members on a type.'

这就是我所拥有的:

型号:

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

映射:

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"]))

有人知道如何使它正常工作吗?

1 个答案:

答案 0 :(得分:3)

您将需要执行以下操作

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

您有方法的地方

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

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

AutoMapper似乎不支持在属性中添加点或在数组中建立索引。

如果您想完全内联,则可以

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