Map one Class properties to two different class properties using Mapster

1.7k views Asked by At

I have 3 classes with the name of Employee, EmployeeTwo, and EmployeeThree, I wanted to map Employee to EmployeeTwo and Employee to EmployeeThree.

Following are the Classes. I also have tried to define the AdaptMember attribute on the Employee Class property but it only defines one and I have to map it with two different.

Note: I cannot define any attribute to the EmployeeTwo and EmployeeThree classes because this comes from the API and it can be regenrate.

public class Employee
{ 
    [AdaptMember(nameof(EmployeeTwo.EmployeeID))]
    public int ID { get; set; } 
    [AdaptMember(nameof(EmployeeTwo.EmployeeName))]
    public string Name { get; set; } 
}

public class EmployeeTwo
{
    
    public int EmployeeID { get; set; }

    
    public string EmployeeName { get; set; }

}

public class EmployeeThree
{
    
    public int EmployeeThreeID { get; set; }
    
    public string EmployeeThreeName { get; set; }
}

Any help is really appriciated.

1

There are 1 answers

0
Laith Sa'd Al-Deen On BEST ANSWER

As I understand you, you want to make a custom object mapping using mapster. If you want to make a custom mapping you need to create a class:

using Mapster;

namespace Application.Mapsters
{
    public class Config : ICodeGenerationRegister
    {
        public void Register(CodeGenerationConfig config)
        {
            TypeAdapterConfig<Employee, EmployeeTwo>
                .NewConfig()
                .Map(dst => dst.EmployeeID, src => src.ID)
                .Map(dst => dst.EmployeeName, src => src.Name);
        }
    }
}

For instance, follow this example to see how to make a custom mapping using mapster:

https://floatincode.net/2021/07/26/mapster-generate-dto-async-after-map-actions-dependency-injection/