Skip to content

ForCtorParam should be inherited #4312

@ruben-ivre

Description

@ruben-ivre

When using records (or a class with a constructor), when you define ForCtorParam in a base class, you also need to specify it in every derived class again. I understand that derived classes could have less or more constructor parameters, but I think it's a safe assumption to reuse the same constructor param mapping as the base class if the name and type of the parameter matches.
Otherwise, this makes using inheritance with constructors quite cumbersome, as I have to repeat the same mappings over and over.

Source/destination types

public record class SourceBase(bool IsPublic) {}
public record class SourceDerived(bool IsPublic) : SourceBase(IsPublic) {}

public record class TargetBase(string Visibility) {}
public record class TargetDerived(string Visibility) : TargetBase(Visibility) {}

Mapping configuration

CreateMap<SourceBase, TargetBase>()
	.ForCtorParam(nameof(TargetBase.Visibility), o => o.MapFrom(s => s.IsPublic ? "public" : "private"))
	.IncludeAllDerived();
CreateMap<SourceDerived, TargetDerived>();

Version: 12.0.1

Expected behavior

Above configuration should be valid, understanding the the same mapping done in the base class for the Visibility parameter can be reused again in the derived type.

Actual behavior

Above configuration fails the validation, force me to repeat the ForCtorParam in the base class in each of the derived ones.

Steps to reproduce

https://dotnetfiddle.net/i8nhRQ

var config = new MapperConfiguration(cfg =>
{
    cfg.AddProfile<TestProfile>();
});
config.AssertConfigurationIsValid();
var mapper = config.CreateMapper();
var result = mapper.Map<TargetDerived>(new SourceDerived(true));
Console.WriteLine(result.Visibility);

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions