我在Source
和destination
命名空间中为Employee
和Department
类提供了匹配的数据结构,主要区别如下:
Employee
将Employee
的嵌套属性设为List
。Employee
已将嵌套属性Employee
设为Array
。我想映射这两个类,但Employee
属性导致StackOverflowException
。
namespace Soure
{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public List<Department> dept1 { get; set; }
public List<Employee> employees { get; set; }
public int age { get; set; }
public Employee()
{
this.Id = 1;
this.Name = "Test Employee Name";
this.age = 10;
}
}
public class Department
{
public int Id { get; set; }
public string DeptName { get; set; }
public Department()
{
Id = 2;
DeptName = "Test Dept";
}
}
}
namespace destination
{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public int age { get; set; }
public Departments[] dept1 { get; set; }
public Employee[] employees { get; set; }
}
public class Departments
{
public int Id { get; set; }
public string DeptName { get; set; }
}
}
这显示了我如何使用AutoMapper进行映射
static void Main(string[] args)
{
var emp1 = new Soure.Employee();
var emp2 = new Soure.Employee();
var dept = new Soure.Department();
var depts = new List<Soure.Department>();
depts.Add(dept);
emp1.dept1 = depts;
emp2.dept1 = depts;
var empList = new List<Soure.Employee>() { emp1, emp2 }.AsQueryable();
Mapper.CreateMap<Soure.Employee, destination.Employee>();
Mapper.CreateMap<Soure.Department, destination.Departments>();
Mapper.AssertConfigurationIsValid();
var xu = Mapper.Map<IEnumerable<Soure.Employee>, IEnumerable<destination.Employee>>(empList);
var mappedEmp = empList.Project().To<destination.Employee>();
}