c# - 取消映射源属性时强制抛出异常

标签 c# automapper

在 AutoMapper 2.2.1 中,有什么方法可以配置我的映射,以便在未明确忽略属性时抛出异常?例如,我有以下类和配置:

public class Source
{
    public int X { get; set; }
    public int Y { get; set; }
    public int Z { get; set; }
}

public class Destination
{
    public int X { get; set; }
    public int Y { get; set; }
}


// Config
Mapper.CreateMap<Source, Destination>();

我收到此配置的行为是设置了 Destination.XDestination.Y 属性。此外,如果我测试我的配置:

Mapper.AssertConfigurationIsValid();

然后我将不会收到任何映射异常。我希望发生的是 AutoMapperConfigurationException 被抛出,因为 Source.Z 没有被明确忽略。

我希望这样我必须显式忽略 Z 属性,以便 AssertConfiguartionIsValid 无异常地运行:

Mapper.CreateMap<Source, Destination>()
      .ForSourceMember(m => m.Z, e => e.Ignore());

目前,AutoMapper 不会抛出异常。如果我没有明确指定 Ignore,我希望它抛出异常。我该怎么做?

最佳答案

这是断言所有源类型属性都已映射的方法:

public static void AssertAllSourcePropertiesMapped()
{
    foreach (var map in Mapper.GetAllTypeMaps())
    {
        // Here is hack, because source member mappings are not exposed
        Type t = typeof(TypeMap);
        var configs = t.GetField("_sourceMemberConfigs", BindingFlags.Instance | BindingFlags.NonPublic);
        var mappedSourceProperties = ((IEnumerable<SourceMemberConfig>)configs.GetValue(map)).Select(m => m.SourceMember);

        var mappedProperties = map.GetPropertyMaps().Select(m => m.SourceMember)
                                  .Concat(mappedSourceProperties);

        var properties = map.SourceType.GetProperties(BindingFlags.Instance | BindingFlags.Public);

        foreach (var propertyInfo in properties)
        {
            if (!mappedProperties.Contains(propertyInfo))
                throw new Exception(String.Format("Property '{0}' of type '{1}' is not mapped", 
                                                  propertyInfo, map.SourceType));
        }
    }
}

它检查所有配置的映射并验证每个源类型属性是否定义了映射(映射或忽略)。

用法:

Mapper.CreateMap<Source, Destination>();
// ...
AssertAllSourcePropertiesMapped();

抛出异常

Property 'Int32 Z' of type 'YourNamespace.Source' is not mapped

如果您忽略该属性,一切都很好:

Mapper.CreateMap<Source, Destination>()
      .ForSourceMember(s => s.Z, opt => opt.Ignore());
AssertAllSourcePropertiesMapped();

关于c# - 取消映射源属性时强制抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15409871/

相关文章:

C# WPF 拖放列表框 MVVM

c# - 自动映射器:忽略条件

c# - 为什么 AutoMapper 不使用 ProjectTo 映射二级导航属性?

c# - 如何在解决方案中将 Automapper 4.2.1 升级到 6.1.1。我缺少什么?

c# - Ninject 的 UnitOfWork 模式应该使用什么选项

c# - 基于文本框动态更新WPF Slider

c# - 如何通过C#解析markdown

c# - BouncyCaSTLe PrivateKey 到 X509Certificate2 PrivateKey

c# - 如何在 .Net Core Web API 项目中对使用 Mapper 的方法进行单元测试

c# - AutoMapper:一对多 -> 多对多