Search code examples
c#automapperautomapper-6

Automapper 6.2.2 conditional unflattening?


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);

Solution

  • 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