2011-05-30 50 views
2

我需要将一些值从一个类映射到一个数组。例如: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); 

尝试,但我得到这个错误:

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?

回答

5

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

    }