I would like to setup an Automapper mapping that follows the following rules.
- If the “in place” destination syntax is not used, map a particular member to a value
- If an object is passed in, then use the destination value
I’ve tried this every way I can think of. Something like this:
Mapper.CreateMap<A, B>()
.ForMember(dest => dest.RowCreatedDateTime, opt => {
opt.Condition(dest => dest.DestinationValue == null);
opt.UseValue(DateTime.Now);
});
This always maps the value. Essentially what I want is this:
c = Mapper.Map<A, B>(a, b); // does not overwrite the existing b.RowCreatedDateTime
c = Mapper.Map<B>(a); // uses DateTime.Now for c.RowCreatedDateTime
Note: A does not contain a RowCreatedDateTime.
What are my options here? It’s very frustrating since there appears to be no documentation on the Condition method, and all the google results seem to be focused around where the source value is null, rather than the destination.
EDIT:
Thanks to Patrick, he got me on the right track..
I figured out a solution. If anyone has a better way of doing this, please let me know. Note I had to reference dest.Parent.DestinationValue rather than dest.DestinationValue. For some reason, dest.DestinationValue is always null.
.ForMember(d => d.RowCreatedDateTime, o => o.Condition(d => dest.Parent.DestinationValue != null))
.ForMember(d => d.RowCreatedDateTime, o => o.UseValue(DateTime.Now))
I believe you need to set up two mappings: one with the
Condition(which determines IF a mapping should be performed) and one which defines what to do if theConditionreturns true. Something like this: