Automapper-数组的具体对象 [英] Automapper - concrete object to array

查看:79
本文介绍了Automapper-数组的具体对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

必须转换为

[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'的异常. ----> System.NullReferenceException:对象引用未设置为对象的实例.

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.

有任何线索可以通过AutoMapper解决吗?

Any clue to solve this with AutoMapper?

推荐答案

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

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

    }

这篇关于Automapper-数组的具体对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆