concrete object to array
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?
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]));
}
链接地址: http://www.djcxy.com/p/37400.html
上一篇: 自动映射器和深度加载
下一篇: 具体对象到数组