Skip to content

Commit

Permalink
Correct merge for references
Browse files Browse the repository at this point in the history
  • Loading branch information
artemiusgreat committed May 13, 2023
1 parent ceb81b3 commit 6f50383
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 5 deletions.
2 changes: 1 addition & 1 deletion Libs/ExpressionMapper.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<PropertyGroup>
<IsPackable>true</IsPackable>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<Version>1.0.0</Version>
<Version>1.0.1</Version>
<Description>Simpler alternative to Automapper.</Description>
<Authors>artemiusgreat</Authors>
<Copyright>indemos.com</Copyright>
Expand Down
9 changes: 6 additions & 3 deletions Libs/Mapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,12 @@ private static Func<TI, TO, TO> CreateMerge()
{
if (sourceMembers.TryGetValue(o.Name, out var sourceProperty))
{
return sourceProperty.Type.IsValueType ?
Expression.Bind(o, sourceProperty) :
Expression.Bind(o, Expression.Coalesce(sourceProperty, Expression.Property(output, o)));
var isValue = sourceProperty.Type.IsValueType;
var isNullable = Nullable.GetUnderlyingType(sourceProperty.Type);

return isNullable is not null || isValue is false ?
Expression.Bind(o, Expression.Coalesce(sourceProperty, Expression.Property(output, o))) :
Expression.Bind(o, sourceProperty);
}

return Expression.Bind(o, Expression.Property(output, o));
Expand Down
5 changes: 4 additions & 1 deletion Tests/Maps.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ public class Maps
public class A
{
public int Id { get; set; }
public int? Count { get; set; }
public string Name { get; set; }
}

public class B
{
public int Id { get; set; }
public int? Count { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public A Link { get; set; }
Expand All @@ -35,11 +37,12 @@ public void MergeSameTypes()
public void Merge()
{
var source = new A { Id = 1 };
var destination = new B { Id = 2, Name = "2", Link = new A { Id = 3 }};
var destination = new B { Id = 2, Count = 5, Name = "2", Link = new A { Id = 3 }};

var merge = Mapper<A, B>.Merge(source, destination);

Assert.Equal(1, merge.Id);
Assert.Equal(5, merge.Count);
Assert.Equal("2", merge.Name);
Assert.Equal(3, merge.Link.Id);
Assert.Equal(destination.Link, merge.Link);
Expand Down

0 comments on commit 6f50383

Please sign in to comment.