为在automaticpper中具有类型的所有成员配置约定

时间:2018-06-01 17:48:29

标签: automapper automapper-6

我的所有域模型都有字段public CurrencyId CurrencyId {get; set;}。我的所有观看模型都已归档public CurrencyVm Currency {get; set;}。 Automapper知道如何Map<CurrencyVm>(CurrencyId)。如何设置自动约定,所以我不必.ForMember(n => n.Currency, opt => opt.MapFrom(n => n.CurrencyId));

1 个答案:

答案 0 :(得分:2)

ForAllMaps就是答案,谢谢@LucianBargaoanu。这段代码有点用,但在所有情况下都没有经过测试。另外我不知道如何检查选择属性之间是否存在映射。

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