MapsterMapper / MapsterMapper/Mapster

DestinationTransform.EmptyCollectionIfNull overrides explicit null mapping

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

Nobody has claimed this yet.

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

Description

When DestinationTransform.EmptyCollectionIfNull is configured globally via config.Default, it still overrides explicitly defined mappings that return null.
This behavior is unexpected because explicit mappings (via .Map(...)) should take precedence over global/default transforms.

- Mapster version: 10.0.8-pre06
- .NET version: net10.0

```csharp
class FooDto
{
public string[]? Strings { get; set; }
}

record Foo(string?[] Strings);

public class DestinationTransformTests
{
[Fact]
public void ExplicitNullMapping_ShouldNotBeOverridden_ByDefaultEmptyCollectionTransform()
{
// Configure
var config = new TypeAdapterConfig();

config.Default
.AddDestinationTransform(DestinationTransform.EmptyCollectionIfNull);

config.NewConfig()
.Map(d => d.Strings, _ => (string[]?)null);

// Arrange
var fooDto = new Foo([]);

// Act
var foo = fooDto.Adapt(config);

// Assert
foo.Strings.ShouldBeNull();
}
}
```

## Expected behavior
The explicit mapping:
```csharp
.Map(d => d.Strings, _ => (string[]?)null)
```
should be respected, resulting in foo.Strings == null.

## Actual behavior
foo.Strings is transformed into an empty array, meaning that EmptyCollectionIfNull is applied after the explicit mapping and overrides it.

## Notes
The transform is registered on config.Default, not per-type.
This suggests that global destination transforms are applied at a stage where they override even explicit mapping results.
This makes it impossible to explicitly map a collection property to null when EmptyCollectionIfNull is enabled globally.

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 with the DestinationTransform.EmptyCollectionIfNull registration and the DestinationTransformTests case shown in the issue, then reproduce the behavior using the provided TypeAdapterConfig and Foo/FooDto types. Trace when the global destination transform runs relative to the explicit .Map(...) result; done means the test passes with foo.Strings remaining null.

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
Quiet
Clarity
Clearly specified
Newbie friendliness
68/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.