From 773f64adac3925878c966990ef26d49290c9ba2a Mon Sep 17 00:00:00 2001 From: chaowlert Date: Sun, 22 Nov 2020 20:48:24 +0700 Subject: [PATCH] fix #281 null propagation --- src/Mapster.Tests/WhenFlattening.cs | 19 +++++++++++++++++++ src/Mapster/Utils/ExpressionEx.cs | 2 ++ 2 files changed, 21 insertions(+) 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); }