2011-05-30 46 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])); 

    }