Skip to content

DestinationTransform.EmptyCollectionIfNull overrides explicit null mapping #952

@moikot

Description

@moikot

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
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<Foo, FooDto>()
            .Map(d => d.Strings, _ => (string[]?)null);

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

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

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

Expected behavior

The explicit mapping:

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions