Force throwing of exception when a source property is unmapped

情到浓时终转凉″ 提交于 2019-12-03 12:59:37

Here is method which asserts that all source type properties are mapped:

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));
        }
    }
}

It checks all configured mappings and verifies that each source type property has mapping defined (either mapped, or ignored).

Usage:

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

That throws exception

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

If you will ignore that property, all is fine:

Mapper.CreateMap<Source, Destination>()
      .ForSourceMember(s => s.Z, opt => opt.Ignore());
AssertAllSourcePropertiesMapped();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!