MapsterMapper / Mapster

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

Value overwritten by re-mapping #677

Closed luczito closed 6 months ago

luczito commented 7 months ago

I have a Domain and Dto layer in my solution which both have the following classes (DomBase, DomDerived, DomPayment & DerivedDomPayment in domain layer):

public class DtoBase
{
    public DtoPayment Payment { get; set; }
}
public class DtoDerived : DtoBase
{
    public new DerivedDtoPayment Payment
    {
        get => (DerivedDtoPayment)base.Payment;
        set => base.Payment = (DtoPayment)value;
    }
} 
public class DtoPayment
{
    public bool Prop { get; set; }
}
public class DerivedDtoPayment : DtoPayment
{
    public bool Test { get; set; }
}

When mapping from one layer to another as:

var dto = new DtoDerived();
dto.Payment = new DerivedDtoPayment();
var domain = dto.Adapt<DomDerived>();
Assert.Equals(domain.Payment.Test, dto.Payment.Test);

I get a "System.InvalidCastException : Unable to cast object of type DtoPayment to type DtoDerPayment" error. However when debugging the getter and setter I can see that the value parsed in is the correct DtoDerPayment type, but somehow it is overwritten to the base type before the getter is hit. The structure worked with Automapper and the configs are basically 1-1, but I simply can't wrap my head around a fix for this.