Reputation: 33
Im get stuck with AutoMapper syntax.
How to skip mapping members in the nested class (by condition string is empty)? Im tried following code:
[TestMethod]
public void TestMethod4()
{
var a = new A { Nested = new NestedA { V = 1, S = "A" } };
var b = new B { Nested = new NestedB { V = 2, S = string.Empty } };
Mapper.CreateMap<B, A>();
Mapper.CreateMap<NestedB, NestedA>().ForMember(s => s.S, opt => opt.Condition(src => !string.IsNullOrWhiteSpace(src.S)));
var result = Mapper.Map(b, a);
Assert.AreEqual(2, result.Nested.V); // OK
Assert.AreEqual("A", result.Nested.S); // FAIL: S == null
}
Thanks
Upvotes: 3
Views: 2085
Reputation: 67336
Have you tried using the opt.Skip suggested here.
Mapper.CreateMap<NestedB, NestedA>()
.ForMember(s => s.S, opt => opt.Skip(src => !string.IsNullOrWhiteSpace(src.S)));
EDIT:
After some digging in the source. I see that in the TypeMapObjectMapperRegistry class (the one that handles mappings for nested objects) it returns before seeing if the the destination value is needed to be preserved (using UseDestinationValue). Otherwise, I was going to suggest this:
Mapper.CreateMap<B, A>();
Mapper.CreateMap<NestedB, NestedA>()
.ForMember(s => s.S, opt => opt.Condition(src => !string.IsNullOrWhiteSpace(src.S)))
.ForMember(s => s.S, opt => opt.UseDestinationValue());
I found this where Jimmy seems to address the core issue here.
So, from what I've found, there doesn't seem to be a way to use Condition and UseDestinationValue at the same time.
Upvotes: 2