具有下划线/ PascalCase属性的自动映射命名约定

时间:2016-04-01 17:15:14

标签: c# automapper

我想用Automapper绘制2个类:

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

为什么?

2 个答案:

答案 0 :(得分:3)

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不知道你在说什么映射。

答案 1 :(得分:2)

借助GitHub中的AutoMapper项目:

  

设置约定后尝试CreateMap。

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