首页 > 解决方案 > AutoMapper - 将单个整数映射到数组

问题描述

我在旧数据库中有 12 个整数代表 12 个月,我需要将它们映射到数组/列表。问题是我不确定如何将模型中的数组初始化为 12 大小,以便对其进行映射。

这是我正在尝试做的事情:

模型:

public class Year 
{
    public int[] Months { get; set; }   //How do I initialize to 12?
}

映射:

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

我到处搜索模型中的预初始化数组,但在语法上找不到任何东西。

标签: c#automapper

解决方案


很简单:

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

我还建议删除 setter,将其设为只读属性 - 不会改变在数组本身中设置单个项目的能力。


推荐阅读