Mapster Map IEnumerable<Interface> to IEnumerable<Interface> Using Specific Classes

44 Views Asked by At

I have the following basic model scenario where an interface is enforce multiple common properties on various classes. Each class also has it's own additional properties as well which are not specified in the common interface.

public enum PersonType
{
    Employee = 0,
    Customer = 1
}

public interface IPerson
{
    string Name { get; set; }
    PersonType PersonType { get; set; }
}

public class Employee : IPerson
{
    public string Name { get; set; }
    public PersonType PersonType { get; set; } = PersonType.Employee;
    public string ManagerName { get; set; }
}

public class Customer : IPerson
{
    public string Name { get; set; }
    public PersonType PersonType {get;set; } = PersonType.Customer;
    public string ContactNumber { get; set; }
}

Models that need to map to/from each other.

public class DbModel
{
    public IEnumerable<IPerson> Persons { get; set; }
}

public class WebDto
{
    public IEnumerable<IPerson> Person { get; set; }
}

When I Adapt() using the following map I loose all properties in the destination except those that are specified on the interface. Given the simple map configuration this would be expected.

TypeAdapterConfig<DbModel, WebDto>.NewConfig()
    .MapToConstructor(true);

However, is there any way to inspect the source object and construct the correct destination object? Meaning, in the scenario presented, could I say if the source.PersonType == Customer then construct a Customer class and so on?

Thanks!

0

There are 0 best solutions below