diff --git a/src/Mapster.Tests/WhenPerformingDestinationTransforms.cs b/src/Mapster.Tests/WhenPerformingDestinationTransforms.cs index cc84b155..fe767b8f 100644 --- a/src/Mapster.Tests/WhenPerformingDestinationTransforms.cs +++ b/src/Mapster.Tests/WhenPerformingDestinationTransforms.cs @@ -95,6 +95,19 @@ public void Adapter_Destination_Transform_CreateNewIfNull() destination.Set.Count.ShouldBe(0); } + [TestMethod] + public void Explicit_Null_Mapping_Is_Not_Overridden_By_EmptyCollectionIfNull() + { + var config = new TypeAdapterConfig(); + config.Default.AddDestinationTransform(DestinationTransform.EmptyCollectionIfNull); + config.NewConfig() + .Map(d => d.Strings, _ => (string[]?)null); + + var destination = new ExplicitNullSource([]).Adapt(config); + + destination.Strings.ShouldBeNull(); + } + #region TestClasses public class SimplePoco @@ -145,6 +158,13 @@ public class CollectionDto public ISet Set { get; set; } } + public record ExplicitNullSource(string?[] Strings); + + public class ExplicitNullDestination + { + public string[]? Strings { get; set; } + } + #endregion } diff --git a/src/Mapster/Adapters/BaseAdapter.cs b/src/Mapster/Adapters/BaseAdapter.cs index b519a334..3e3c72d0 100644 --- a/src/Mapster/Adapters/BaseAdapter.cs +++ b/src/Mapster/Adapters/BaseAdapter.cs @@ -497,7 +497,7 @@ internal Expression CreateAdaptExpression(Expression source, Type destinationTyp : CreateAdaptExpressionCore(_source, destinationType, arg, mapping, destination); //transform(adapt(_source)); - if (notUsingDestinationValue) + if (notUsingDestinationValue && !HasExplicitMemberMap(mapping, arg)) { var transform = arg.Settings.DestinationTransforms.Find(it => it.Condition(exp.Type)); if (transform != null) @@ -521,5 +521,16 @@ internal Expression CreateAdaptExpression(Expression source, Type destinationTyp return exp.To(destinationType); } + + static bool HasExplicitMemberMap(MemberMapping? mapping, CompileArgument arg) + { + if (mapping?.DestinationMember == null) + return false; + + var memberName = mapping.DestinationMember.Name; + return arg.Settings.Resolvers.Any(resolver => + !resolver.IsChildPath && + resolver.DestinationMemberName.Equals(memberName, StringComparison.InvariantCultureIgnoreCase)); + } } }