Automapper - concrete object to array

霸气de小男生 提交于 2019-12-06 07:04:35

问题


I need to map some values from a class to an array. For example:

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

must be converted to

[age, cars]

I tried with this

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

but i get this error:

Using mapping configuration for Employee to System.Int32[] Exception of type 'AutoMapper.AutoMapperMappingException' was thrown. ----> System.NullReferenceException : Object reference not set to an instance of an object.

Any clue to solve this with AutoMapper?


回答1:


I found a good solution. Using the ConstructUsing feature is the way to go.

    [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]));

    }


来源:https://stackoverflow.com/questions/6179903/automapper-concrete-object-to-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!