I will not say that this is the best (experienced or design) approach, but it works:
public static class AutoExtensions { public static IMappingExpression Ignore(this IMappingExpression expression, Func<PropertyInfo, bool> filter) { foreach (var propertyName in expression .TypeMap .SourceType .GetProperties() .Where(filter) .Select(x=>x.Name)) { expression.ForMember(propertyName, behaviour => behaviour.Ignore()); } return expression; } }
You can configure your mapper this way (for these patterns):
public class Client { public string LUName { get; set; } public string Dno { get; set; } } public class ClientDTO { public string LUName { get; set; } public string Dno { get; set; } }
and check it as follows:
private static void ConfigAndTestMapper() { var config = new MapperConfiguration(cfg =>{ cfg.CreateMap(typeof (Client), typeof (ClientDTO)) .Ignore(x => x.Name.StartsWith("LU")); }); var mapper = config.CreateMapper(); var result = mapper.Map<ClientDTO>(new Client() {LUName = "Name", Dno = "Dno"}); var isIgnored = result.LUName == null; }
PS: itβs also quite βhackerβ, because it is trying to display all kinds of properties (readonly / non-public, etc.), so take it with salt.
source share