How to define conditional mapping in Mapster with different types of source field?

121 Views Asked by At

I'm trying to use Mapster for mapping and can't use conditional mapping in case of different field types in different condition 'branches'.

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'.

Of course I can just slap .AfterMapping() and perform anything with custom code, but is there Mapster way to do that?

1

There are 1 best solutions below

0
MauroBV On

The way you are using the map method is correct. The error is because the third parameter expression does not support the use of .HasValue(). The way to solve it is to compare it against the null value.

Solution:

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

I ran into a similar problem, trying to parse an enum to long in the validation expression.