c# - 具有下划线/PascalCase 属性的 Automapper 命名约定

标签 c# automapper

我有 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; }
    }
}

这是我的自动映射器配置:

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();
        }
    }
}

异常(exception):

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

为什么?

最佳答案

在 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>();
    });
}

关于c# - 具有下划线/PascalCase 属性的 Automapper 命名约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36362157/

相关文章:

c# - 回发后不显示用户控件

c#、列表框、stackOverflow 异常

c# - C++ 非托管包装器在 Web 项目/iis 中不起作用

c# - Mongo C# 驱动程序在连接失败时尝试重新连接

c# - 在 XmlDocument 中按名称搜索节点

c# - 使用 AutoMapper 映射对象

c# - 将 AutoMapper 从 3 更新到 4 打破了继承映射

c# - 是否可以使用自动映射器将 IDataReader 映射到嵌套 DTO?

automapper - 使用 AutoMapper 合并两个对象以生成第三个对象

c# - 在 ASP.NET Core 2.1 中使用 ConstructUsingServiceLocator() 时出现 AutoMapperMappingException