diff --git a/src/Mapster.Tests/WhenCtorNullableParamMapping.cs b/src/Mapster.Tests/WhenCtorNullableParamMapping.cs index e1884624..a2632043 100644 --- a/src/Mapster.Tests/WhenCtorNullableParamMapping.cs +++ b/src/Mapster.Tests/WhenCtorNullableParamMapping.cs @@ -1,5 +1,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Shouldly; +using System; using System.Collections.Generic; namespace Mapster.Tests @@ -82,6 +83,27 @@ public void NullableCtorPropagationCurrentWorkWithDestinationTransform() foo.Strings.ShouldNotBeNull(); } + + /// + /// https://github.com/MapsterMapper/Mapster/issues/954 + /// + [TestMethod] + public void MappingValueTypeParametrUsingDefaultValueCorrect() + { + // Arrange + var src = new DateTimeFoo954(DateTime.Today); + + // Assert + Should.NotThrow(() => + { + var foo = src.Adapt(); + + foo.Timestamp.ShouldBe(src.Timestamp); + }); + } + + + #region Immutable classes with private setters, map via ctors private abstract class AbstractDomainTestClass { @@ -119,6 +141,18 @@ public DomainTestClass( #region DTO classes + public class DateTimeFooDto954 + { + public DateTime Timestamp { get; set; } + + public DateTimeFooDto954(DateTime timestamp = default(DateTime)) + { + this.Timestamp = timestamp; + } + } + + record DateTimeFoo954(DateTime Timestamp); + class FooDto943 { public string[] Strings { get; set; } diff --git a/src/Mapster/Adapters/BaseClassAdapter.cs b/src/Mapster/Adapters/BaseClassAdapter.cs index d719409e..6d12a934 100644 --- a/src/Mapster/Adapters/BaseClassAdapter.cs +++ b/src/Mapster/Adapters/BaseClassAdapter.cs @@ -222,11 +222,27 @@ protected Expression CreateInstantiationExpression(Expression source, ClassMappi { arg.Context.NullChecks.UnionWith(members.Where(x=>x.Getter != null).Select(x=>(x.Getter,arg))); var parameterInfo = (ParameterInfo)member.DestinationMember.Info!; - var defaultConst = parameterInfo.IsOptional + Expression defaultConst; + Expression getter; + +#if NETSTANDARD2_0 + try + { + defaultConst = parameterInfo.IsOptional && parameterInfo.DefaultValue != null ? Expression.Constant(parameterInfo.DefaultValue, member.DestinationMember.Type) : parameterInfo.ParameterType.CreateDefault(); + } + catch (FormatException) + { + defaultConst = parameterInfo.ParameterType.CreateDefault(); + } - Expression getter; +#else + defaultConst = parameterInfo.IsOptional && parameterInfo.DefaultValue != null + ? Expression.Constant(parameterInfo.DefaultValue, member.DestinationMember.Type) + : parameterInfo.ParameterType.CreateDefault(); +#endif + if (member.Getter == null) { getter = defaultConst; @@ -352,6 +368,6 @@ protected static Expression SetValueTypeAutoPropertyByReflection(MemberMapping m new[] { member.Destination, memberAsObject }); } - #endregion +#endregion } }