mappingautomapperdescendantmapster

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.


Solution

  • You need to use ShallowCopyForSameType, AutoMapper will perform deep copy only declared types, Mapster perform deep copy for all types.