Mapster - 从基础 class 映射后代 classes

Mapster - mapping descendant classes from base class

类:

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; }
}

代码:

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);

如果您 运行 代码,您将看到 SourceType 和 DestType 不同。我如何实现它们相同? Mapster 将部门映射为 Department class(祖先)而不是 DepartmentA class(后代)。

在此示例中,我知道 emp.Department 中有后代,但在我的应用程序中我不知道。所以这个问题的解法一定是通用的。

我试图在 AutoMapper 中解决这个问题。得到了相同的结果。 正如@Prolog 在下面所写的那样,AutoMapper 正在运行。我更新了主要代码。

如果有人解决了 Mapster 中的问题,我仍然很感兴趣。

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