Skip to content

Polymorphic mapping of nested property to null property. #794

Closed
@vchc

Description

@vchc

Hi all!

Mapster 7.4.0

I encountered some strange behavior with mapping of polymorphic nested properties.
The task is to map a nested polymorhic property of source (DTO) to the nested polymorphic property of destination.

Expected result of mapping for actual types is.
BaseDTO -> Base
DerivedDTO-> Derived

When destination nested property is null it is always mapped as base class even when the source nested property is derived class.
DerivedDTO-> Derived - not works when destination property is null

May be it is expected, but it looks like a bug for me. Or may be there is a mistake in my configuration?

public class Base
{
    public string SomeBaseProperty { get; set; }
}

public class BaseDTO
{
    public string SomeBasePropertyDTO { get; set; }
}

public class Derived : Base
{
    public string SomeDerivedProperty { get; set; }
}

public class DerivedDTO : BaseDTO
{
    public string SomeDerivedPropertyDTO { get; set; }
}

public class Container
{
    public Base Nested { get; set; }
}

public class ContainerDTO
{
    public BaseDTO NestedDTO { get; set; }
}

            config
                .NewConfig<ContainerDTO, Container>()
                .Map(dest => dest.Nested, src => src.NestedDTO )
                .IgnoreNonMapped(true)
                .IgnoreNullValues(true);

            config
                .NewConfig<BaseDTO, Base>()
                .Map(dest => dest.SomeBaseProperty , src => src.SomeBasePropertyDTO)
                .Include<DerivedDTO, Base>()
                .IgnoreNonMapped(true)
                .IgnoreNullValues(true);

            config
                .NewConfig<DerivedDTO, Derived>()
                .Map(dest => dest.SomeDerivedProperty , src => src.SomeDerivedPropertyDTO)
                .IgnoreNonMapped(true)
                .IgnoreNullValues(true);

            config
                .NewConfig<DerivedDTO, Base>()
                .MapWith(src => src.Adapt<Derived>());

//Case 1 (works)
var container = new();
var containerDTO = new();

//Nested is populated with Base
container.Nested = new();
containerDTO.NestedDTO = new DerivedDTO();

//Polymorphism works for Nested property
mapper.Map<ContainerDTO, Container>(containerDTO, container);

//Case 2 (does not work)
var container = new();
var containerDTO = new();

//Nested is null
container.Nested = null;
containerDTO.NestedDTO = new DerivedDTO();

//Polymorphism does not work for Nested property. It is always Base.
mapper.Map<ContainerDTO, Container>(containerDTO, container);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions