'Mapping from entity to dto with inheritence

I ran into this case where i get a ParentEntity from the Database and want to map it to the ParentDto. Pretty standard. The Parent classes are abstract and have about 10 properties. There are 4 derived classes with 1-2 extra Properties each.

Usually i just do this kind of Stuff with a switch expression and dont worry about the duplicated code, but its normally 1-2 properties and 1-2 cases. Is there any clean looking solution to this?

public abstract record ParentEntity();
public record Child1Entity() : ParentEntity;
public record Child2Entity() : ParentEntity;
public record Child3Entity() : ParentEntity;

public abstract record ParentDto();
public record Child1Dto() : ParentDto;
public record Child2Dto() : ParentDto;
public record Child3Dto() : ParentDto;

var dbEntity = new ParentEntity(); // comes from the Database and can be child1, child2, child3

ParentDto dto = dbEntity switch
{
    Child1Entity e => new Child1Dto(),
    Child2Entity e => new Child2Dto(),
    Child3Entity e => new Child3Dto(),
};

This is what i usually do

ParentDto dto2 = dbEntity switch
{
    Child1Entity e => new Child1Dto(Prop1 = e.Prop1, Prop2 = e.Prop2... Child1Prop = e.Child1Prop),
    Child2Entity e => new Child2Dto(Prop1 = e.Prop1, Prop2 = e.Prop2... Child2Prop = e.Child2Prop),
    Child3Entity e => new Child3Dto(Prop1 = e.Prop1, Prop2 = e.Prop2... Child3Prop = e.Child3Prop),
};

This and much worse is what would happen if i did this with a switch expression.

var dt3 = new ParentDto();
dto3.Prop1 = dbEntity.Prop1;
dto3.Prop2 = dbEntity.Prop2;
...
dto3.Prop10 = dbEntity.Prop10;

if(dbEntity is Child1Entity child1)
    dto3.Child1Prop = child1.Child1Prop
if (dbEntity is Child1Entity child2)
    dto3.Child2Prop = child2.Child2Prop
if (dbEntity is Child1Entity child3)
    dto3.Child2Prop = child3.Child3Prop

This doesnt even compile because ParentDto is abstract. This is how I would not duplicate code. But its not particularly pretty either.

Is there any way to do this succinctly? Preferably without AutoMapper.



Solution 1:[1]

Without using Automapper and such, I'd suggest to create a method to convert one in another. Something like the example above, clean and readable:

public static ParentDTO ToParentDTO(ParentEntity myEntity)
{
    return new ParentDTO()
    {
        Prop1 = myEntity.Prop1,
        (...)
    };
}

Also, you can use LINQ for full approach

var parentDTO = parents.Select(x => ToParentDTO(x)).ToList();

( refer to this reply Cleanest Way To Map Entity To DTO With Linq Select? )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 i.Dio