From c670690c40a5f1371e9adcf0c21e767e2b196ac7 Mon Sep 17 00:00:00 2001 From: DocSvartz Date: Thu, 25 Jun 2026 12:03:03 +0500 Subject: [PATCH] fix: quick fix Custom converter supporting from nullable ValueType --- .../WhenMappingNullablePrimitives.cs | 40 +++++++++++++++++++ src/Mapster/Adapters/NullableAdapter.cs | 19 ++++++++- 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/src/Mapster.Tests/WhenMappingNullablePrimitives.cs b/src/Mapster.Tests/WhenMappingNullablePrimitives.cs index 8d0fec3f..47aa080d 100644 --- a/src/Mapster.Tests/WhenMappingNullablePrimitives.cs +++ b/src/Mapster.Tests/WhenMappingNullablePrimitives.cs @@ -158,8 +158,48 @@ public void MappingNullTuple() result.Application.ShouldBeNull(); } + [TestMethod] + public void CustomConverterWorkWithNullablePrimitiveTypes() + { + TypeAdapterConfig config = new TypeAdapterConfig(); + config.NewConfig().MapWith(src => Helper992.ParseToNullableBool(src)); + config.Compile(); + + var src = new Source992 { Prop1 = "yes" }; + var result = src.Adapt(config); + + result.Prop1.ShouldBe(true); + + } + + #region TestClasses + static class Helper992 + { + public static bool? ParseToNullableBool(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + return null; + + return value.Trim().ToLower() switch + { + "true" or "t" or "yes" or "1" => true, + "false" or "f" or "no" or "0" => false, + _ => null + }; + } + } + + public class Source992 + { + public string? Prop1 { get; set; } + } + + public class Destination992 + { + public bool? Prop1 { get; set; } + } public class Output414 { diff --git a/src/Mapster/Adapters/NullableAdapter.cs b/src/Mapster/Adapters/NullableAdapter.cs index bfc7d836..598a2192 100644 --- a/src/Mapster/Adapters/NullableAdapter.cs +++ b/src/Mapster/Adapters/NullableAdapter.cs @@ -1,4 +1,5 @@ -using Mapster.Utils; +using Mapster.Models; +using Mapster.Utils; using System.Linq.Expressions; namespace Mapster.Adapters @@ -19,6 +20,22 @@ protected override bool CanInline(Expression source, Expression? destination, Co protected override Expression? CreateInlineExpression(Expression source, CompileArgument arg, bool IsRequiredOnly = false) { + if (arg.ExplicitMapping) + { + LambdaExpression? Convert = null; + + TypeAdapterRule? getsettings; + arg.Context.Config.RuleMap.TryGetValue(new TypeTuple(arg.SourceType, arg.DestinationType), out getsettings); + + if (getsettings != null) + if (arg.MapType == MapType.MapToTarget) + Convert = getsettings.Settings.ConverterToTargetFactory(arg); + else + Convert = getsettings.Settings.ConverterFactory(arg); + if (Convert != null) + return Convert.Apply(arg.MapType, source); + } + var _source = source.Type.IsNullable() ? Expression.Convert(source, source.Type.GetGenericArguments()[0]) : source;