Skip to content

Commit c620ed9

Browse files
authored
Merge pull request #753 from DocSvartz/Fix-Init-property-in-derived-class
Fix issue #672 - AmbiguousMatchException
2 parents 3bf9e6b + a8baff8 commit c620ed9

File tree

2 files changed

+64
-1
lines changed

2 files changed

+64
-1
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
using Microsoft.VisualStudio.TestTools.UnitTesting;
2+
using Shouldly;
3+
4+
namespace Mapster.Tests;
5+
6+
[TestClass]
7+
public class WhenMappingInitProperty
8+
{
9+
10+
#region Tests
11+
/// <summary>
12+
/// From Issue #672
13+
/// https://github.com/MapsterMapper/Mapster/issues/672
14+
/// </summary>
15+
[TestMethod]
16+
public void WhenMappingToHiddenandNewInitFieldDestination()
17+
{
18+
var source = new Source672() { Id = 156};
19+
var c = source.Adapt<BDestination>();
20+
var s = source.Adapt(new BDestination());
21+
22+
((ADestination)c).Id.ShouldBe(156);
23+
s.Id.ShouldBe(156);
24+
}
25+
26+
[TestMethod]
27+
public void WhenMappingToHiddenandNewInitFieldWithConstructUsing()
28+
{
29+
TypeAdapterConfig<Source672, BDestination>.NewConfig().ConstructUsing(_ => new BDestination());
30+
31+
32+
var source = new Source672() { Id = 256 };
33+
var c = source.Adapt<BDestination>();
34+
var s = source.Adapt(new BDestination());
35+
36+
((ADestination)c).Id.ShouldBe(256);
37+
s.Id.ShouldBe(256);
38+
}
39+
40+
41+
#endregion Tests
42+
43+
44+
#region TestClasses
45+
46+
class Source672
47+
{
48+
public long Id { get; init; }
49+
}
50+
51+
class ADestination
52+
{
53+
public int Id { get; init; }
54+
}
55+
56+
class BDestination : ADestination
57+
{
58+
public new long Id { get; init; }
59+
}
60+
61+
62+
#endregion TestClasses
63+
}

src/Mapster/Adapters/ClassAdapter.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ private static Expression SetValueByReflection(MemberMapping member, MemberExpre
183183
var typeofExpression = Expression.Constant(member.Destination!.Type);
184184
var getPropertyMethod = typeof(Type).GetMethod("GetProperty", new[] { typeof(string) })!;
185185
var getPropertyExpression = Expression.Call(typeofExpression, getPropertyMethod,
186-
Expression.Constant(member.DestinationMember.Name));
186+
Expression.Constant(member.DestinationMember.Name, member.DestinationMember.Type));
187187
var setValueMethod =
188188
typeof(PropertyInfo).GetMethod("SetValue", new[] { typeof(object), typeof(object) })!;
189189
var memberAsObject = adapt.To(typeof(object));

0 commit comments

Comments
 (0)