簡體   English   中英

這是 AutoMapper 的 PascalCase 命名約定正則表達式的錯誤嗎?

[英]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對其進行測試,我得到兩個匹配項, ShippingAddress1

呵呵呵! 我的源屬性名稱是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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM