0

I've recently updated to the latest version of Automapper (6.2.2) to take advantage of unflattening via .ReverseMap(). Everything seemed to be going well until I realized it was always creating an empty object regardless of whether or not the flattened source properties had values. Totally understandable, but to prevent this I tried adding a condition, like so:

cfg.CreateMap<Entity, DTO>()
    .ReverseMap()
        .ForMember(d => d.UnflattenedType, o => o.Condition(s => s.FlattenedId.HasValue));

This doesn't seem to work though and I've been searching for a solution for too long now.

So my question is, is there a way to conditionally prevent automapper from initializing a destination object (unflattening) when using ReverseMap?

UPDATE

I've come up with a workaround by doing the following, but I'm still looking for a proper solution.

cfg.CreateMap<Entity, DTO>()
    .ReverseMap()
        .AfterMap((s, d) => d.UnflattenedType = s.FlattenedId.HasValue ? d.UnflattenedType : null);

2 Answers2

1

According to the developers of Automapper, this is not possible as of version 6.2.2. Check out this issue I posted on their GitHub for more info:

https://github.com/AutoMapper/AutoMapper/issues/2498

0

Have you tried ForPath?

cfg.CreateMap<Entity, DTO>()
    .ReverseMap()
        .ForPath(d => d.UnflattenedType, o => o.MapFrom(s => s.FlattenedId.HasValue ? s.FlattenedId : null));
ngruson
  • 1,176
  • 1
  • 13
  • 25
  • I haven't tried this yet, but I assume this would result in only the Id property being unflattened? I'd like to find a solution where all available properties are unflattened if a certain condition is met without having to specify each property I want to unflatten. Thank you though! –  Jan 16 '18 at 15:07