[英]Is this a bug with AutoMapper's PascalCase naming convention regex?
我正在尝试利用 AutoMapper 以便不必手动编写大量代码映射。 这似乎适用于除这一类以外的所有其他内容:
CreateMap<AccountConnection, AccountConnectionDto>();
CreateMap<Account, AccountDto>();
CreateMap<Address, AddressDto>() // <--- this one
.ForMember(dest => dest.StreetAddress1, opt => opt.MapFrom(src => src.street_address_1))
.ForMember(dest => dest.StreetAddress2, opt => opt.MapFrom(src => src.street_address_2))
.ForMember(dest => dest.StreetAddress3, opt => opt.MapFrom(src => src.street_address_3));
如果我不手动映射这 3 个成员,那么当我运行config.AssertConfigurationIsValid();
它抛出。
Exception Details: AutoMapper.AutoMapperConfigurationException:
Unmapped members were found. Review the types and members below.
Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type
For no matching constructor, add a no-arg ctor, add optional arguments, or map all of the constructor parameters
=================================================
Address -> AddressDto (Destination member list)
Proj.Data.Address -> Proj.API.AddressDto (Destination member list)
Unmapped properties:
StreetAddress1
StreetAddress2
StreetAddress3
我在我的个人资料中使用以下命名约定:
SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
DestinationMemberNamingConvention = new PascalCaseNamingConvention();
这些是唯一在属性名称中带有数字的属性,因此我在 GitHub 上挖掘了 AutoMapper 源代码,并找到了我在我的项目中使用的 PascalCaseNamingConvention 的正则表达式。 这是:
(\\p{Lu}+(?=$|\\p{Lu}[\\p{Ll}0-9])|\\p{Lu}?[\\p{Ll}0-9]+)
如果我抛出在https://regex101.com 中,然后根据我的财产名称ShippingAddress1
对其进行测试,我得到两个匹配项, Shipping
和Address1
。
呵呵呵! 我的源属性名称是shipping_address_1
(不要问),所以这行不通。 这是因为我的命名约定被破坏了,还是 PascalCaseNamingConvention 应该将shipping_address_x
匹配到ShippingAddressX
? (在 AutoMapper github 上提出了一个问题,但他们要求新人先在 SO 上发帖,看看人们是否认为这是一个合法的错误)。
从我下面详细的测试中,我相信指定的命名约定是错误的:
public class Address
{
public string StreetAddress1 { get; set; }
}
public class AddressDto
{
public string street_address_1 { get; set; }
}
static void Main(string[] args)
{
// Prints nothing
PerformMappingTest(new PascalCaseNamingConvention(), new LowerUnderscoreNamingConvention());
// Prints "Test"
PerformMappingTest(new LowerUnderscoreNamingConvention(), new PascalCaseNamingConvention());
Console.ReadKey();
}
static void PerformMappingTest(INamingConvention source, INamingConvention destination)
{
var config = new MapperConfiguration(cfg => {
cfg.SourceMemberNamingConvention = source;
cfg.DestinationMemberNamingConvention = destination;
cfg.CreateMap<Address, AddressDto>();
});
var mapper = config.CreateMapper();
var address = new Address { StreetAddress1 = "Test" };
var addressDto = mapper.Map<Address, AddressDto>(address);
Console.WriteLine(addressDto.street_address_1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.