简体   繁体   中英

Mapster - mapping descendant classes from base class

Classes:

public class Department
{
    public string Name { get; set; }
}

public class DepartmentA : Department
{
    public string NameA { get; set; }
}

public class Employee
{
    public string Name { get; set; }
    public int Salary { get; set; }
    public string Address { get; set; }
    public Department Department { get; set; }
}

public class EmployeeDTO
{
    public string Name { get; set; }
    public int Salary { get; set; }
    public string Address { get; set; }
    public Department Department { get; set; }
}

Code:

DepartmentA departmentA = new DepartmentA { NameA = "depA", Name = "dep" };

Employee emp = new Employee
{
        Name = "James",
        Salary = 20000,
        Address = "London",
        Department = departmentA
};
        
//Mapster
var empDTO = emp.Adapt<EmployeeDTO>();

//AutoMapper
//var config = new MapperConfiguration(cfg => cfg.CreateMap<Employee, EmployeeDTO>());

//var mapper = config.CreateMapper();
//EmployeeDTO empDTO = mapper.Map<EmployeeDTO>(emp);

Console.WriteLine("SourceType:" + emp.Department.GetType().Name);

Console.WriteLine("DestType:" + empDTO.Department.GetType().Name);

If you run the code you will see that SourceType and DestType are not the same. How do I achieve that they are the same? Mapster mapps department as Department class (ancestor) and not as DepartmentA class (descendant).

In this example I know that there is descendant in emp.Department but in my app I won't know. So the solution of this problem must be generic.

I tried to solve this problem in AutoMapper. Got the same results. As @Prolog wrote below, in AutoMapper is working. I updated main code.

I am still interested if someone solved issue in Mapster.

您需要使用ShallowCopyForSameType ,AutoMapper 将仅对声明的类型执行深复制, Mapster对所有类型执行深复制。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM