diff --git a/src/Mapster.Tests/WhenMappingDerived.cs b/src/Mapster.Tests/WhenMappingDerived.cs index 01bfac41..e6399389 100644 --- a/src/Mapster.Tests/WhenMappingDerived.cs +++ b/src/Mapster.Tests/WhenMappingDerived.cs @@ -44,6 +44,82 @@ public void WhenMappingDerivedWithoutMembers() Assert.AreEqual(inputEntity.Id, result.Id); } + /// + /// https://github.com/MapsterMapper/Mapster/issues/794 + /// + [TestMethod] + public void WhenMapToTargetDerivedWithNullRegression() + { + var config = new TypeAdapterConfig(); + + config + .NewConfig() + .Map(dest => dest.Nested, src => src.NestedDTO) + .IgnoreNonMapped(true) + .IgnoreNullValues(true); + config + .NewConfig() + .Map(dest => dest.SomeBaseProperty, src => src.SomeBasePropertyDTO) + .Include() + .IgnoreNonMapped(true) + .IgnoreNullValues(true); + + config + .NewConfig() + .Map(dest => dest.SomeDerivedProperty, src => src.SomeDerivedPropertyDTO) + .IgnoreNonMapped(true) + .IgnoreNullValues(true); + config + .NewConfig() + .MapWith(src => src.Adapt()); + + + var container = new Container794(); + var containerDTO = new ContainerDTO794(); + + container.Nested = null; + containerDTO.NestedDTO = new DerivedDTO794(); + + containerDTO.Adapt(container, config); + + (container.Nested is Derived794E).ShouldBeTrue(); // is not Base794 type, MapWith is working when Polymorphic mapping to null + } + + internal class Derived794E : Derived794 + { + + } + + internal class Base794 + { + public string SomeBaseProperty { get; set; } + } + + internal class BaseDTO794 + { + public string SomeBasePropertyDTO { get; set; } + } + + internal class Derived794 : Base794 + { + public string SomeDerivedProperty { get; set; } + } + + internal class DerivedDTO794 : BaseDTO794 + { + public string SomeDerivedPropertyDTO { get; set; } + } + + internal class Container794 + { + public Base794 Nested { get; set; } + } + + internal class ContainerDTO794 + { + public BaseDTO794 NestedDTO { get; set; } + } + internal class BaseDto { public long Id { get; set; } diff --git a/src/Mapster/Adapters/BaseAdapter.cs b/src/Mapster/Adapters/BaseAdapter.cs index 366f1eeb..cf3e5cb5 100644 --- a/src/Mapster/Adapters/BaseAdapter.cs +++ b/src/Mapster/Adapters/BaseAdapter.cs @@ -201,9 +201,12 @@ protected Expression CreateBlockExpressionBody(Expression source, Expression? de drvdDest, Expression.TypeAs(destination, tuple.Destination)); blocks.Add(drvdDestAssign); - cond = Expression.AndAlso( - cond, - Expression.NotEqual(drvdDest, Expression.Constant(null, tuple.Destination))); + + // fix by https://github.com/MapsterMapper/Mapster/issues/794 + // This can be removed if it does not cause any other bugs. + // cond = Expression.AndAlso( + // cond, + // Expression.NotEqual(drvdDest, Expression.Constant(null, tuple.Destination))); } var adaptExpr = CreateAdaptExpressionCore(drvdSource, tuple.Destination, arg, destination: drvdDest);