AutoMapper问题用于映射IQueryable映射中的嵌套数组

时间:2015-04-27 15:55:13

标签: c# asp.net asp.net-mvc nhibernate automapper

我在Sourcedestination命名空间中为EmployeeDepartment类提供了匹配的数据结构,主要区别如下:

  • 来源EmployeeEmployee的嵌套属性设为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>();
}

0 个答案:

没有答案