MapsterMapper / MapsterMapper/Mapster
Can't use conditional mapping with different types of source field
Nobody has claimed this yet.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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