Skip to content

Commit cb28269

Browse files
committed
Support for conditionally mapping complex type properties to null when overwriting
1 parent 71a73da commit cb28269

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

AgileMapper.UnitTests/Configuration/WhenMappingToNull.cs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
namespace AgileObjects.AgileMapper.UnitTests.Configuration
22
{
3+
using System;
34
using Shouldly;
45
using TestClasses;
56
using Xunit;
@@ -54,5 +55,41 @@ public void ShouldRestrictAConfiguredMapToNullConditionBySourceType()
5455
matchingResult.Address.ShouldBeNull();
5556
}
5657
}
58+
59+
[Fact]
60+
public void ShouldOverwriteAPropertyToNull()
61+
{
62+
using (var mapper = Mapper.CreateNew())
63+
{
64+
mapper.WhenMapping
65+
.Over<Address>()
66+
.If(ctx => ctx.Target.Line1 == null)
67+
.MapToNull();
68+
69+
var nonMatchingSource = new CustomerViewModel
70+
{
71+
Id = Guid.NewGuid(),
72+
AddressLine1 = "Places!"
73+
};
74+
var target = new Customer { Address = new Address { Line1 = "Home!" } };
75+
76+
mapper.Map(nonMatchingSource).Over(target);
77+
78+
target.Address.ShouldNotBeNull();
79+
target.Address.Line1.ShouldBe("Places!");
80+
81+
var matchingSource = new CustomerViewModel { Id = Guid.NewGuid() };
82+
83+
mapper.Map(matchingSource).Over(target);
84+
85+
target.Address.ShouldBeNull();
86+
87+
var nullAddressTarget = new Customer();
88+
89+
mapper.Map(matchingSource).Over(nullAddressTarget);
90+
91+
target.Address.ShouldBeNull();
92+
}
93+
}
5794
}
5895
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,22 @@
11
namespace AgileObjects.AgileMapper.Configuration
22
{
3+
using System.Linq.Expressions;
4+
using Members;
5+
using ObjectPopulation;
6+
37
internal class MapToNullCondition : UserConfiguredItemBase
48
{
59
public MapToNullCondition(MappingConfigInfo configInfo)
610
: base(configInfo)
711
{
812
}
13+
14+
protected override Expression GetConditionOrNull(IMemberMapperData mapperData, CallbackPosition position)
15+
{
16+
mapperData.Context.UsesMappingDataObjectAsParameter =
17+
ConfigInfo.ConditionUsesMappingDataObjectParameter;
18+
19+
return base.GetConditionOrNull(mapperData, position);
20+
}
921
}
1022
}

0 commit comments

Comments
 (0)