Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions src/Mapster.Tests/WhenMappingNullablePrimitives.cs
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,48 @@ public void MappingNullTuple()
result.Application.ShouldBeNull();
}

[TestMethod]
public void CustomConverterWorkWithNullablePrimitiveTypes()
{
TypeAdapterConfig config = new TypeAdapterConfig();
config.NewConfig<string?, bool?>().MapWith(src => Helper992.ParseToNullableBool(src));
config.Compile();

var src = new Source992 { Prop1 = "yes" };
var result = src.Adapt<Destination992>(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
{
Expand Down
19 changes: 18 additions & 1 deletion src/Mapster/Adapters/NullableAdapter.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Mapster.Utils;
using Mapster.Models;
using Mapster.Utils;
using System.Linq.Expressions;

namespace Mapster.Adapters
Expand All @@ -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;
Expand Down
Loading