Skip to content

Commit b3f79e8

Browse files
authored
fix: use correct nullable types when referencing named mappings (#1237)
1 parent de3b332 commit b3f79e8

File tree

3 files changed

+57
-1
lines changed

3 files changed

+57
-1
lines changed

src/Riok.Mapperly/Descriptors/MappingBuilderContext.cs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,16 @@ bool ignoreDerivedTypes
175175
Location? diagnosticLocation = null
176176
)
177177
{
178-
return FindMapping(key) ?? FindOrBuildMapping(key.NonNullable(), options, diagnosticLocation);
178+
if (FindMapping(key) is { } mapping)
179+
return mapping;
180+
181+
// if a user mapping is referenced
182+
// build it with the exact types
183+
// as it may expect a nullable source type
184+
if (key.Configuration.UseNamedMapping != null)
185+
return BuildMapping(key, options, diagnosticLocation);
186+
187+
return FindOrBuildMapping(key.NonNullable(), options, diagnosticLocation);
179188
}
180189

181190
/// <summary>

test/Riok.Mapperly.Tests/Mapping/ObjectPropertyUseNamedMappingTest.cs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -347,4 +347,34 @@ class B
347347
);
348348
return TestHelper.VerifyGenerator(source);
349349
}
350+
351+
[Fact]
352+
public Task ShouldPassNullValueToNullableUserMappingMethod()
353+
{
354+
var source = TestSourceBuilder.MapperWithBodyAndTypes(
355+
"""
356+
[MapProperty(nameof(A.Value), nameof(B.Value), Use = nameof(MapString)]
357+
public partial B Map(A source);
358+
359+
[UserMapping(Default = false)]
360+
private string MapString(string? source)
361+
=> source ?? "(null)";
362+
""",
363+
"""
364+
class A
365+
{
366+
public string? Value { get; }
367+
public string? Value2 { get; }
368+
}
369+
""",
370+
"""
371+
class B
372+
{
373+
public string Value { set; }
374+
public string Value2 { set; }
375+
}
376+
"""
377+
);
378+
return TestHelper.VerifyGenerator(source);
379+
}
350380
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
//HintName: Mapper.g.cs
2+
// <auto-generated />
3+
#nullable enable
4+
public partial class Mapper
5+
{
6+
[global::System.CodeDom.Compiler.GeneratedCode("Riok.Mapperly", "0.0.1.0")]
7+
public partial global::B Map(global::A source)
8+
{
9+
var target = new global::B();
10+
if (source.Value2 != null)
11+
{
12+
target.Value2 = source.Value2;
13+
}
14+
target.Value = MapString(source.Value);
15+
return target;
16+
}
17+
}

0 commit comments

Comments
 (0)