C# AutoMapper大写下划线映射问题:无需ForMember实现字段匹配
问题:AutoMapper如何映射
USER_ID到UserId(无需手动ForMember配置) 我在使用C# AutoMapper时碰到过一个很头疼的命名映射问题:源数据类的属性是大写下划线格式的USER_ID,目标Dto类的属性是帕斯卡命名的UserId。一开始我用了常规的命名约定配置:
cfg.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention(); cfg.DestinationMemberNamingConvention = new PascalCaseNamingConvention();
结果映射完全不生效,反而把Dto的属性改成Userİd(带点的土耳其语小写i)时,映射突然正常了。显然这是默认命名约定对大写开头的下划线格式处理有问题,而且我不想用ForMember逐个手动配置映射,那该怎么解决?
解决方案:自定义INamingConvention
核心思路是针对大写下划线格式的源属性,自定义一个命名约定类,让AutoMapper能正确解析USER_ID并映射到UserId。我写了一个UpperUnderscoreNamingConvention类,专门处理这种大写+下划线的命名格式,同时解决了字母I的大小写转换问题(这就是之前改成Userİd能成功的原因——默认转换会把大写I变成土耳其语的小写ı,而不是普通的i):
public class UpperUnderscoreNamingConvention : INamingConvention { private readonly Regex _splittingExpression = new Regex(@"[\p{Lu}0-9]+(?=_?)"); public Regex SplittingExpression { get { return _splittingExpression; } } public string SeparatorCharacter { get { return "_"; } } public string ReplaceValue(Match match) { // 把大写I转换成普通小写i,避免默认的土耳其语字符转换问题 return match.Value.Equals("I") ? "i" : match.Value.ToLowerInvariant(); } }
配置代码
把自定义的命名约定替换掉原来的LowerUnderscoreNamingConvention,配置如下:
Mapper.Initialize(cfg => { cfg.SourceMemberNamingConvention = new UpperUnderscoreNamingConvention(); cfg.DestinationMemberNamingConvention = new PascalCaseNamingConvention(); });
这样配置后,AutoMapper就能正确把USER_ID映射到UserId了,完全不需要手动写ForMember来指定映射关系。
内容的提问来源于stack exchange,提问作者cod3r
相关产品推荐
相关产品推荐

