Search code examples
c#automapper

Apply in Automapper a Condition over Multiple Map Expressions Without Repetition


I need to apply the following condition ForAllMembers(o => o.Condition((src, dest, srcMember) => srcMember != null)) over multiple map expressions. My objective is to have an object overriding the contents of another object using mapper but only where the value is not null, like this var object = mapper.Map(newData, existingData);.

My current code looks like this but with more map expressions:

public class MappingConfig
{
    public static MapperConfiguration RegisterMaps()
    {
        return new MapperConfiguration(config =>
        {
            config.CreateMap<PermissaoEntity, PermissaoVO>().ReverseMap()
            .ForAllMembers(o => o.Condition((src, dest, srcMember) => srcMember != null));
            config.CreateMap<SystemCategoria, CategoriaVO>().ReverseMap()
            .ForAllMembers(o => o.Condition((src, dest, srcMember) => srcMember != null));
        });
    }
}

It works but needs lots of copying and pasting.


Solution

  •     public static MapperConfiguration RegisterMaps() {
        return new MapperConfiguration(config => {
            config.CreateMap<PermissaoEntity, PermissaoVO>().ReverseMap();
            config.CreateMap<SystemCategoria, CategoriaVO>().ReverseMap();
    
            config.Internal().ForAllMaps((typeMap, mappingExpression) =>
                mappingExpression.ForAllMembers(o => o.Condition((src, dest, srcMember) => srcMember != null))
            );
        });
    

    ForAllMaps() was the answer I was looking for but this answer is also a good one.