MapsterMapper / Mapster

A fast, fun and stimulating object to object Mapper
MIT License
4.32k stars 329 forks source link

Mapping to derived type not working as expected #664

Closed luczito closed 9 months ago

luczito commented 10 months ago

Suppose I have 2 base classes with derived classes as:

public abstract class Base{
      public int Value {get; set;}
}

public abstract class DtoBase{
         public int Value {get; internal set; }

         protected DtoBase(int value)
        {
                 Value = value;
        } 
}

public class DerivedBase{

         public DerivedBase()
         {}

         public DerivedBase(int value)
          {
                Value = value;
          }
}

public class DerivedDtoBase{

            public DerivedDtoBase()
            {}

             public DerivedDtoBase(int value)
            {
                Value = value;
            }
}

With the config:

TypeAdapterConfig.NewConfig<Base, DtoBase>()
           .Include<DerivedBase, DerivedDtoBase>();
TypeAdapterConfig.NewConfig<DtoBase, Base>()
           .Include<DerivedDtoBase, DerivedBase>();

When mapping from DerivedBase to BaseDto i expect it to map to the DerivedDtoBase, instead i get the error:

Error while compiling source=DerivedBase
destination=DtoBase
type=Map
Cannot convert immutable type, please consider using 'MapWith' or 'ConstructUsing' method to create mapping.

Is there a way to configure the mapping logic to automatically map to the corresponding derived Dto class and vice versa since this is a scenario that is common on our platform?

Or do i need to specifically define the config as:

TypeAdapterConfig.NewConfig<DerivedBase, DtoBase>()
          .ConstructUsing(src => new DerivedDtoBase(src.Value));

Which works but is quite a lot of custom configuration considering the amount of times we perform this type of derived mapping.