Automapper - 具体对象到数组

时间:2011-05-30 19:07:07

标签: automapper

我需要将一些值从类映射到数组。例如:

    public class Employee
    {
        public string name;
        public int age;
        public int cars;
    }

必须转换为

[age, cars]

我试过这个

var employee = new Employee()
        {
            name = "test",
            age = 20,
            cars = 1
        };

        int[] array = new int[] {};

        Mapper.CreateMap<Employee, int[]>()
            .ForMember(x => x,
                options =>
                {
                    options.MapFrom(source => new[] { source.age, source.cars });
                }
            );

        Mapper.Map(employee, array);

但是我收到了这个错误:

  

使用Employee到System.Int32 []的映射配置   抛出了“AutoMapper.AutoMapperMappingException”类型的异常。     ----&GT; System.NullReferenceException:未将对象引用设置为对象的实例。

使用AutoMapper解决这个问题的任何线索?

1 个答案:

答案 0 :(得分:6)

我找到了一个很好的解决方案。使用ConstructUsing功能是可行的方法。

    [Test]
    public void CanConvertEmployeeToArray()
    {

        var employee = new Employee()
        {
            name = "test",
            age = 20,
            cars = 1
        };

        Mapper.CreateMap<Employee, int[]>().ConstructUsing(
                x => new int[] { x.age, x.cars }
            );

        var array = Mapper.Map<Employee, int[]>(employee);

        Assert.That(employee.age, Is.EqualTo(array[0]));
        Assert.That(employee.cars, Is.EqualTo(array[1]));

    }