Force throwing of exception when a source property

2019-03-27 00:39发布

问题:

In AutoMapper 2.2.1, is there any way I can configure my mappings so that when a property is not explicitly ignored, an exception is thrown? For example, I have the following classes and configuration:

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

The behavior I receive with this configuration is that the Destination.X and Destination.Y properties are set. Furthermore, if I test my configuration:

Mapper.AssertConfigurationIsValid();

Then I will receive no mapping exceptions. What I would like to happen is that an AutoMapperConfigurationException is thrown because Source.Z is not explicitly ignored.

I would like it so that I have to explicitly ignore the Z property in order for AssertConfiguartionIsValid to run without exceptions:

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

Currently, AutoMapper does not throw an exception. I would like it to throw an exception if I do not explicitly specify the Ignore. How can I do this?

回答1:

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


标签: c# AutoMapper