Skip to content

Commit

Permalink
fix #263 fix when source path is Dictionary
Browse files Browse the repository at this point in the history
  • Loading branch information
chaowlert committed Aug 19, 2020
1 parent e3872a1 commit 27babf3
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
14 changes: 14 additions & 0 deletions src/Mapster.Tests/WhenMappingWithPath.cs
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,20 @@ public void TestMappingToSelf()
p1.Secret.ShouldBeNull();
}

[TestMethod]
public void TestMappingFromDictionary()
{
var config = new TypeAdapterConfig();
config.NewConfig<Post, Post>()
.Map(nameof(Post.Dic) + ".Name", nameof(Post.Dic) + ".Name");

var p1 = new Post{ Dic = new Dictionary<string, string> { { "Name", "test"}, {"Secret" , "password" }} };
var p2 = new Post();
p1.Adapt(p2, config);

p2.Dic["Name"].ShouldBe("test");
}

public class Poco
{
public Guid Id { get; set; }
Expand Down
4 changes: 2 additions & 2 deletions src/Mapster/Settings/ValueAccessingStrategy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public static class ValueAccessingStrategy
{
var config = arg.Settings;
var resolvers = config.Resolvers;
if (resolvers == null || resolvers.Count == 0)
if (resolvers.Count == 0)
return null;

var invokes = new List<Tuple<Expression, Expression>>();
Expand Down Expand Up @@ -205,7 +205,7 @@ private static IEnumerable<string> GetDeepUnflattening(IMemberModel destinationM
{
var config = arg.Settings;
var resolvers = config.Resolvers;
if (resolvers == null || resolvers.Count == 0)
if (resolvers.Count == 0)
return null;
var dictType = source.Type.GetDictionaryType();
if (dictType == null)
Expand Down
10 changes: 10 additions & 0 deletions src/Mapster/Utils/ExpressionEx.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,16 @@ public static Expression PropertyOrFieldPath(Expression expr, string path)
private static Expression PropertyOrField(Expression expr, string prop)
{
var type = expr.Type;
var dictType = type.GetDictionaryType();
if (dictType?.GetGenericArguments()[0] == typeof(string))
{
var method = typeof(MapsterHelper).GetMethods()
.First(m => m.Name == nameof(MapsterHelper.GetValueOrDefault) && m.GetParameters()[0].ParameterType.Name == dictType.Name)
.MakeGenericMethod(dictType.GetGenericArguments());

return Expression.Call(method, expr.To(type), Expression.Constant(prop));
}

if (type.GetTypeInfo().IsInterface)
{
var allTypes = type.GetAllInterfaces();
Expand Down

0 comments on commit 27babf3

Please sign in to comment.