Configuring convention for all members with type in automapper

1k Views Asked by At

All my domain models have field public CurrencyId CurrencyId {get; set;}. All my view models have filed public CurrencyVm Currency {get; set;}. Automapper knows how to Map<CurrencyVm>(CurrencyId). How can I setup automatic convention, so I do not have to .ForMember(n => n.Currency, opt => opt.MapFrom(n => n.CurrencyId));?

1

There are 1 best solutions below

11
On BEST ANSWER

ForAllMaps is the answer, thanks @LucianBargaoanu. This code kinda works, but hasn't been tested in all cases. Also I do not know how to check if exists mapping between choosen properties.

        configuration.ForAllMaps((map, expression) =>
        {
            if (map.IsValid != null)
            {
                return; // type is already mapped (or not)
            }

            const string currencySuffix = "Id";
            var currencyPropertyNames = map.SourceType
                .GetProperties()
                .Where(n => n.PropertyType == typeof(CurrencyId) && n.Name.EndsWith(currencySuffix))
                .Select(n => n.Name.Substring(0, n.Name.Length - currencySuffix.Length))
                .ToArray();
            expression.ForAllOtherMembers(n =>
            {
                if (currencyPropertyNames.Contains(n.DestinationMember.Name, StringComparer.OrdinalIgnoreCase))
                {
                    n.MapFrom(n.DestinationMember.Name + currencySuffix);
                }
            });
        });