我有 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/