Skip to content

Commit

Permalink
fix: map init only collection in existing target mapping correctly (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
latonz committed Mar 20, 2024
1 parent 3bf7bba commit c9b4b17
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,11 @@ MemberPath targetMemberPath
// if the member is readonly
// and the target and source path is readable,
// we try to create an existing target mapping
if (targetMemberPath.Member.CanSet || !targetMemberPath.Path.All(op => op.CanGet) || !sourceMemberPath.Path.All(op => op.CanGet))
if (
targetMemberPath.Member is { CanSet: true, IsInitOnly: false }
|| !targetMemberPath.Path.All(op => op.CanGet)
|| !sourceMemberPath.Path.All(op => op.CanGet)
)
{
return false;
}
Expand Down
21 changes: 21 additions & 0 deletions test/Riok.Mapperly.Tests/Mapping/EnumerableExistingTargetTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,4 +107,25 @@ public void EnumerableMappingExistingTargetDisabledShouldDiagnostic()
"""
);
}

[Fact]
public void MapToExistingInitOnlyCollection()
{
var source = TestSourceBuilder.MapperWithBodyAndTypes(
"partial void Map(A source, B target);",
"class A { public ICollection<string> Subs { get; } = new List<string>(); }",
"class B { public ICollection<string> Subs { get; init; } = new List<string>(); }"
);
TestHelper
.GenerateMapper(source)
.Should()
.HaveSingleMethodBody(
"""
foreach (var item in source.Subs)
{
target.Subs.Add(item);
}
"""
);
}
}

0 comments on commit c9b4b17

Please sign in to comment.