具有 underscore/PascalCase 属性的 Automapper 命名约定

Automapper naming convention with underscore/PascalCase properties

我有 2 个 类 我想用 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 项目的帮助下:

Try the CreateMap after you set the convention.

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