MapsterMapper/Mapster

Can't use conditional mapping with different types of source field

Offen

#673 geöffnet am 01.02.2024

 (3 Kommentare) (0 Reaktionen) (0 zugewiesene Personen)C# (312 Forks)batch import
help wantedimprovement

Repository-Metriken

Stars
 (3.995 Sterne)
PR-Merge-Metriken
 (Durchschn. Merge 12T 15h) (10 gemergte PRs in 30 T)

Beschreibung

For example there are 2 classes:

public class Source
{
    public int? IntValue { get; set; }
    public string StringValue { get; set; } = "Some Value";
}

public class Destination
{
    public string Mapped { get; set; } = string.Empty;
}

The task is put in Mapped string representation of IntValue if it's not null, otherwise use StringValue. I assume configuration should look like (according to Mapster docs):

TypeAdapterConfig.GlobalSettings
    .NewConfig<Source, Destination>()
    .Map(dest => dest.Mapped, src => src.IntValue, src => src.IntValue.HasValue)
    .Map(dest => dest.Mapped, src => src.StringValue);

But it gives runtime exception:

Mapster.CompileException: Error while compiling
source=Source
destination=Destination
type=Map
 ---> System.InvalidOperationException: No coercion operator is defined between types 'System.Nullable`1[System.Int32]' and 'System.String'.

Is it intended behavior or it's a bug? How to perform conditional mapping in given case Mapster way, without slapping .AfterMapping() and do it with custom code?

Contributor Guide