diff --git a/src/Mapster.Tests/WhenFlattening.cs b/src/Mapster.Tests/WhenFlattening.cs index a80d9858..da7f64d9 100644 --- a/src/Mapster.Tests/WhenFlattening.cs +++ b/src/Mapster.Tests/WhenFlattening.cs @@ -37,6 +37,11 @@ public class E public decimal BClass_Total { get; set; } } + public class F + { + public decimal? BClass_Total { get; set; } + } + public class ModelObject { public DateTime BaseDate { get; set; } @@ -106,6 +111,20 @@ public void PropertyTest_NameWithUnderscore() Assert.IsTrue(e.BClass_Total == 250); } + [TestMethod] + public void PropertyTest_NullPropagation() + { + var f = TypeAdapter.Adapt(new C { BClass = new B { Total = 250 } }); + + Assert.IsNotNull(f); + Assert.IsTrue(f.BClass_Total == 250); + + var f2 = TypeAdapter.Adapt(new C { BClass = null }); + + Assert.IsNotNull(f2); + Assert.IsNull(f2.BClass_Total); + } + [TestMethod] public void ShouldUseNestedObjectPropertyMembers() { diff --git a/src/Mapster/Utils/ExpressionEx.cs b/src/Mapster/Utils/ExpressionEx.cs index fd67f84f..06923eb9 100644 --- a/src/Mapster/Utils/ExpressionEx.cs +++ b/src/Mapster/Utils/ExpressionEx.cs @@ -317,6 +317,8 @@ public static Expression ApplyNullPropagation(this Expression getter) if (expr.CanBeNull()) { var compareNull = Expression.Equal(expr, Expression.Constant(null, expr.Type)); + if (!result.Type.CanBeNull()) + result = Expression.Convert(result, typeof(Nullable<>).MakeGenericType(result.Type)); result = Expression.Condition(compareNull, result.Type.CreateDefault(), result); }