MapsterMapper / MapsterMapper/Mapster

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

Open
#673 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

help wanted improvement
Dominant language
C#
Stars
5.2k
Forks
410
Avg merge
2d 12h
Merged PRs (30d)
6

Description

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](https://github.com/MapsterMapper/Mapster/wiki/Custom-mapping#mapping-with-condition)):

```
TypeAdapterConfig.GlobalSettings
.NewConfig()
.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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the exception with the Source and Destination classes and the TypeAdapterConfig.GlobalSettings mapping shown in the issue. Trace how the two conditional Map calls are compiled when their source expressions have different types. Done means conditional mapping supports the nullable integer-to-string case without requiring AfterMapping, with coverage for the reported configuration.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
backend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.