簡體   English   中英

具有下划線/ PascalCase屬性的自動映射器命名約定

[英]Automapper naming convention with underscore/PascalCase properties

我有兩個要與Automapper映射的類:

namespace AutoMapperApp
{
    public class Class1
    {
        public string Test { get; set; }
        public string property_name { get; set; }
    }
}

namespace AutoMapperApp
{
    public class Class2
    {
        public string Test { get; set; }
        public string PropertyName { get; set; }
    }
}

這是我的Automapper配置:

using AutoMapper;

namespace AutoMapperApp
{
    public static class AutoMapperConfig
    {
        public static MapperConfiguration MapperConfiguration;

        public static void RegisterMappings()
        {
            MapperConfiguration = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Class1, Class2>();
                cfg.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
                cfg.DestinationMemberNamingConvention = new PascalCaseNamingConvention();
            });
        }
    }
}

根據Automapper的Wiki,這應該可以正常工作: https : //github.com/AutoMapper/AutoMapper/wiki/Configuration

但是我的單元測試失敗了:

using Xunit;
using AutoMapperApp;

namespace AutoMapperTest
{
    public class Test
    {
        [Fact]
        public void AssertConfigurationIsValid()
        {
            AutoMapperConfig.RegisterMappings();
            AutoMapperConfig.MapperConfiguration.AssertConfigurationIsValid();
        }
    }
}

例外:

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
=============================================
Class1 -> Class2 (Destination member list)
AutoMapperApp.Class1 -> AutoMapperApp.Class2 (Destination member list)

Unmapped properties:
PropertyName

為什么?

public class AutoMapperConfig
{
  public static void RegisterMappings()
  {
    Mapper.Initialize(cfg =>
    {
      cfg.CreateMap<Class1, Class2>();
      cfg.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
      cfg.DestinationMemberNamingConvention = new PascalCaseNamingConvention();
    });
  }
}

我假設您在app_start方法中調用此方法。 AutoMapperConfig.RegisterMappings();

出於組織目的,如果您不需要像示例中那樣全局通用,則可以將映射分為概要文件,注冊它們並在逐個概要文件的基礎上設置約定。

要回答您的問題,您似乎創建了一個映射器配置,但是沒有初始化它,因此Automapper不知道您在說什么映射。

在GitHub中的AutoMapper項目的幫助下:

設置約定后,請嘗試CreateMap。

public static void RegisterMappings()
{
    MapperConfiguration = new MapperConfiguration(cfg =>
    {
        cfg.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
        cfg.DestinationMemberNamingConvention = new PascalCaseNamingConvention();
        cfg.CreateMap<Class1, Class2>();
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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