Search code examples
c#.net-6.0mapster

Mapster not mapping derived class in a List c#


I have multiple classes implementing a base class, e.g.:

public abstract class Step
{
    public StepId Id {get; set;}
    public string Text {get; set;
    public StepType Type {get;set;}
}

public class SelectionStep : Step 
{
    public List<string> Selections {get; set;}
}

public class NumericStep : Step 
{
}

With the following Mapster configs:

config.NewConfig<SelectionStep, StepResponse>()
    .Map(dest => dest.Selections, src => src.Selections.Select(x => x.Value));

config.NewConfig<Step, StepResponse>()
    .Map(dest => dest.Id, src => src.Id.Value.ToString())
    .Map(dest => dest.Type, src => src.Type.ToString());

When I map from one SelectionStep to StepResponse it's working _mapper.Map<StepResponse>(SelectionStep)

When I map from List<Step> containing both SelectionStep and NumericStep models, it does not use the SelectionStepConfig. _mapper.Map<List<StepResponse>>(List<Step>)


Solution

  • I found the solution.

    I changed my Step configuration to include the SelectionStep see below the new configs.

    config.NewConfig<SelectionStep, StepResponse>()
        .Map(dest => dest.Selections, src => src.Selections.Select(x => x.Value));
    
    config.NewConfig<Step, StepResponse>()
        .Include<SelectionStep, StepResponse>()
        .Map(dest => dest.Id, src => src.Id.Value.ToString())
        .Map(dest => dest.Type, src => src.Type.ToString());