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

Mik*_*ley 8 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>();
Run Code Online (Sandbox Code Playgroud)

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

Mapper.AssertConfigurationIsValid();
Run Code Online (Sandbox Code Playgroud)

然后我将不会收到映射异常.我想要发生的AutoMapperConfigurationException是抛出一个因为Source.Z没有明确忽略.

我想它,所以我必须显式忽略Z属性,以便AssertConfiguartionIsValid无异常地运行:

Mapper.CreateMap<Source, Destination>()
      .ForSourceMember(m => m.Z, e => e.Ignore());
Run Code Online (Sandbox Code Playgroud)

目前,AutoMapper 不会抛出异常.如果我没有明确指定,我希望它抛出异常Ignore.我怎样才能做到这一点?

Ser*_*kiy 5

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

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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

用法:

Mapper.CreateMap<Source, Destination>();
// ...
AssertAllSourcePropertiesMapped();
Run Code Online (Sandbox Code Playgroud)

抛出异常

未映射'YourNamespace.Source'类型的属性'Int32 Z'

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

Mapper.CreateMap<Source, Destination>()
      .ForSourceMember(s => s.Z, opt => opt.Ignore());
AssertAllSourcePropertiesMapped();
Run Code Online (Sandbox Code Playgroud)