Skip to content

polymorphic mappings via [MapDerivedType] on child [UseMapper] classes fail #1989

@ChaseFlorell

Description

@ChaseFlorell

Please do the checklist before filing an issue:

  • I have read the documentation, including the FAQ
  • I can reproduce the bug using the latest prerelease version
  • I have searched existing discussion and issue to avoid duplicates

Describe the bug
Given a child mapping class using the [UseMapper] attribute
When the child mapping exposes a polymorphic mapping as defined with a [MapDerivedType]
Then the parent mapper should use IsAssignableTo instead of IsAssignableFrom

Repro
A link to a repro Gist or GitHub repository or a link to a Mapperly fork with a failing test.

Actual relevant generated code

// Actual relevant code generated by Mapperly
[global::System.CodeDom.Compiler.GeneratedCode("Riok.Mapperly", "4.2.1.0")]
public partial T Map<T>(object source)
{
    return source switch
    {
        global::MapperlyRepro.FooBaseDto x when typeof(T).IsAssignableFrom(typeof(global::MapperlyRepro.FooBase)) => (T)(object)_childMapper.Map(x),
        _ => throw new global::System.ArgumentException($"Cannot map {source.GetType()} to {typeof(T)} as there is no known type mapping", nameof(source)),
    };
}

Expected relevant generated code

// The generated code how you expect it to look like
[global::System.CodeDom.Compiler.GeneratedCode("Riok.Mapperly", "4.2.1.0")]
public partial T Map<T>(object source)
{
    return source switch
    {
        global::MapperlyRepro.FooBaseDto x when typeof(T).IsAssignableTo(typeof(global::MapperlyRepro.FooBase)) => (T)(object)_childMapper.Map(x),
        _ => throw new global::System.ArgumentException($"Cannot map {source.GetType()} to {typeof(T)} as there is no known type mapping", nameof(source)),
    };
}

Environment (please complete the following information):

  • Mapperly Version: 4.3.0-next.6
  • Nullable reference types: Enabled
  • .NET Version: 9.0.305
  • Target Framework: net9.0
  • Compiler Version: 4.14.0-3.25413.5
  • C# Language Version: 13.0
  • IDE: Rider 2025.1.7
  • OS: macOS 15.5 (24F74)

Additional context
I think that when the Parent mapper is generating the switch statement for a child mapper, and the target method is decorated with the [MapDerivedType] attribute, then we need to use the IsAssignableTo method in order to support polymorphism.

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions