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

时间:2013-03-14 12:54:14

标签: 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,我希望它抛出异常。我怎么能这样做?

1 个答案:

答案 0 :(得分: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));
        }
    }
}

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

用法:

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

抛出异常

  

Property&#39; Int32 Z&#39;类型&#39; YourNamespace.Source&#39;未映射

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

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