automapper - 在自动映射器中为所有类型的成员配置约定

标签 automapper automapper-6

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

最佳答案

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

关于automapper - 在自动映射器中为所有类型的成员配置约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50648661/

相关文章:

Automapper 自 Action 图

c# - AutoMapper:如何仅映射匹配的属性名称并忽略所有其他属性名称?

c# - 如何在解决方案中将 Automapper 4.2.1 升级到 6.1.1。我缺少什么?

c# - AutoMapper 在 IQueryable 上调用 ProjectTo<T>() 时抛出 StackOverflowException

lambda - 尝试在业务域和数据域之间转换表达式树是否可行?

c# - AutoMapper.Collections.EntityFramework

asp.net-core - Automapper 和 EF 导航属性

Automapper - 映射子项时需要映射父属性

c# - 当指定条件 != null 时,Automapper 未正确映射 null 列表成员

c# - .Net Core Automapper 缺少类型映射配置或不受支持的映射