Throw exception syntax when source property is not displayed

In AutoMapper 2.2.1, is there a way to configure my mappings so that when an 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 get with this configuration is that the Destination.X and Destination.Y properties are set. Also, if I check my configuration:

 Mapper.AssertConfigurationIsValid(); 

Then I will not get any display exceptions. I would like AutoMapperConfigurationException be thrown because Source.Z is not explicitly ignored.

I would like for me to explicitly ignore the Z property, so that AssertConfiguartionIsValid without exception:

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

AutoMapper does not currently throw an exception. I would like it to throw an exception if I don't explicitly specify Ignore . How can i do this?

+7
source share
1 answer

Here is a method that claims that all properties of a source type are displayed:

 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 a specific mapping (either mapped or ignored).

Using:

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

This is an exception

Property 'Int32 Z' of type 'YourNamespace.Source' not displayed

If you ignore this property, everything is fine:

 Mapper.CreateMap<Source, Destination>() .ForSourceMember(s => sZ, opt => opt.Ignore()); AssertAllSourcePropertiesMapped(); 
+4
source

All Articles