Skip to content

Commit 4ba0e5f

Browse files
committed
we could include a different constructor
1 parent 434703c commit 4ba0e5f

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed

src/AutoMapper/ConstructorMap.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,13 +52,13 @@ public void AddParameter(ParameterInfo parameter, IEnumerable<MemberInfo> source
5252
}
5353
public bool ApplyIncludedMember(IncludedMember includedMember)
5454
{
55-
var typeMap = includedMember.TypeMap;
56-
if (CanResolve || typeMap.ConstructorMap == null)
55+
var includedMap = includedMember.TypeMap.ConstructorMap;
56+
if (CanResolve || includedMap?.Ctor != Ctor)
5757
{
5858
return false;
5959
}
6060
bool canResolve = false;
61-
var includedParams = typeMap.ConstructorMap._ctorParams;
61+
var includedParams = includedMap._ctorParams;
6262
for(int index = 0; index < includedParams.Count; index++)
6363
{
6464
var includedParam = includedParams[index];

src/UnitTests/IMappingExpression/IncludeMembers.cs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1714,4 +1714,41 @@ public void Should_work()
17141714
dest.TheField.ShouldBe(2);
17151715
dest.Level1Field.ShouldBe(3);
17161716
}
1717+
}
1718+
public class IncludeMembersMultipleConstructorMapping : AutoMapperSpecBase
1719+
{
1720+
public class Source
1721+
{
1722+
public int Id;
1723+
public Level1 FieldLevel1;
1724+
}
1725+
public class Level1
1726+
{
1727+
public Level2 FieldLevel2;
1728+
public long Level1Field;
1729+
}
1730+
public class Level2
1731+
{
1732+
public long TheField;
1733+
}
1734+
public record Destination(int Id, long TheField, long Level1Field)
1735+
{
1736+
public Destination(Level2 fieldLevel2, long level1Field) : this(-1, fieldLevel2.TheField, level1Field) { }
1737+
public Destination(long theField) : this(-2, theField, -2) { }
1738+
}
1739+
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
1740+
{
1741+
cfg.ShouldUseConstructor = c => c.IsPublic;
1742+
cfg.CreateMap<Source, Destination>().IncludeMembers(s => s.FieldLevel1);
1743+
cfg.CreateMap<Level1, Destination>(MemberList.None).IncludeMembers(s => s.FieldLevel2);
1744+
cfg.CreateMap<Level2, Destination>(MemberList.None);
1745+
});
1746+
[Fact]
1747+
public void Should_work()
1748+
{
1749+
var dest = Map<Destination>(new Source { Id = 1, FieldLevel1 = new Level1 { Level1Field = 3, FieldLevel2 = new Level2 { TheField = 2 } } });
1750+
dest.Id.ShouldBe(1);
1751+
dest.TheField.ShouldBe(2);
1752+
dest.Level1Field.ShouldBe(3);
1753+
}
17171754
}

0 commit comments

Comments
 (0)