gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 15:56:35 28 4
gpt4 key购买 nike

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

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com