Skip to content

Polymorphic mapping with collections maps only base class properties #793

@neistow

Description

@neistow

This might be related to #776. I have a class hierarchy and a base class DTO that combines all possible properties. When mapping a single item cast to the base class - derived properties are mapped, however, when mapping a collection of the base class items - derived properties are ignored. This doesn't seem like a consistent behavior to me and now it must be fixed with explicit map config.

var items = new List<Base>
{
    new DerivedOne
    {
        Id = Guid.NewGuid(),
        ExtraProperty = "A",
        Property = "a",
    },
    new DerivedTwo
    {
        Id = Guid.NewGuid(),
        Property = "b",
        OtherExtraProperty = "B",
    }
};

// TypeAdapterConfig<Base, BaseDto>.NewConfig()
// .Include<DerivedOne, BaseDto>()
// .Include<DerivedTwo, BaseDto>();

// Here ExtraProperty and OtherExtraProperty are not mapped unless the config above is present
var mappedResultOne= b.Adapt<BaseDto[]>();

// Here OtherExtraProperty is mapped.
var mappedResultTwo = b[1].Adapt<BaseDto>();

public abstract class Base
{
    public Guid Id { get; set; }
    public required string Property { get; set; }
    public abstract string Type { get; protected set; }
}

public class DerivedOne : Base
{
    public required string ExtraProperty { get; set; }
    public override string Type { get; protected set; } = "DerivedOne";
}

public class DerivedTwo : Base
{
    public required string OtherExtraProperty { get; set; }
    public override string Type { get; protected set; } = "DerivedTwo";
}

public record BaseDto
{
    public Guid Id { get; init; }
    public required string Property { get; init; }
    public string? ExtraProperty { get; init; }
    public string? OtherExtraProperty { get; init; }
    public required string Type { get; init; }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions