【问题标题】:Automapper - concrete object to arrayAutomapper - 到数组的具体对象
【发布时间】:2011-05-30 19:07:06
【问题描述】:

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

    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 : 对象引用未设置为对象的实例。

有什么线索可以用 AutoMapper 解决这个问题吗?

【问题讨论】:

    标签: automapper


    【解决方案1】:

    我找到了一个很好的解决方案。使用 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]));
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-31
      • 1970-01-01
      • 2012-01-14
      • 2011-08-08
      • 1970-01-01
      相关资源
      最近更新 更多