diff --git a/src/Mapster.Tests/WhenMappingInitProperty.cs b/src/Mapster.Tests/WhenMappingInitProperty.cs new file mode 100644 index 00000000..4fda1295 --- /dev/null +++ b/src/Mapster.Tests/WhenMappingInitProperty.cs @@ -0,0 +1,63 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Shouldly; + +namespace Mapster.Tests; + +[TestClass] +public class WhenMappingInitProperty +{ + + #region Tests + /// + /// From Issue #672 + /// https://github.com/MapsterMapper/Mapster/issues/672 + /// + [TestMethod] + public void WhenMappingToHiddenandNewInitFieldDestination() + { + var source = new Source672() { Id = 156}; + var c = source.Adapt(); + var s = source.Adapt(new BDestination()); + + ((ADestination)c).Id.ShouldBe(156); + s.Id.ShouldBe(156); + } + + [TestMethod] + public void WhenMappingToHiddenandNewInitFieldWithConstructUsing() + { + TypeAdapterConfig.NewConfig().ConstructUsing(_ => new BDestination()); + + + var source = new Source672() { Id = 256 }; + var c = source.Adapt(); + var s = source.Adapt(new BDestination()); + + ((ADestination)c).Id.ShouldBe(256); + s.Id.ShouldBe(256); + } + + + #endregion Tests + + + #region TestClasses + + class Source672 + { + public long Id { get; init; } + } + + class ADestination + { + public int Id { get; init; } + } + + class BDestination : ADestination + { + public new long Id { get; init; } + } + + + #endregion TestClasses +} diff --git a/src/Mapster/Adapters/ClassAdapter.cs b/src/Mapster/Adapters/ClassAdapter.cs index adf1c60c..407c5a5b 100644 --- a/src/Mapster/Adapters/ClassAdapter.cs +++ b/src/Mapster/Adapters/ClassAdapter.cs @@ -183,7 +183,7 @@ private static Expression SetValueByReflection(MemberMapping member, MemberExpre var typeofExpression = Expression.Constant(member.Destination!.Type); var getPropertyMethod = typeof(Type).GetMethod("GetProperty", new[] { typeof(string) })!; var getPropertyExpression = Expression.Call(typeofExpression, getPropertyMethod, - Expression.Constant(member.DestinationMember.Name)); + Expression.Constant(member.DestinationMember.Name, member.DestinationMember.Type)); var setValueMethod = typeof(PropertyInfo).GetMethod("SetValue", new[] { typeof(object), typeof(object) })!; var memberAsObject = adapt.To(typeof(object));