8

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

AssertConfiguartionIsValid例外なく実行するには、Zプロパティを明示的に無視する必要があるようにしたいと思います。

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

現在、AutoMapperは例外をスローしません。を明示的に指定しない場合は、例外をスローしたいと思いますIgnore。これどうやってするの?

4

1 に答える 1

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

それは例外をスローします

タイプ「YourNamespace.Source」のプロパティ「Int32Z」はマップされていません

そのプロパティを無視する場合は、すべて問題ありません。

Mapper.CreateMap<Source, Destination>()
      .ForSourceMember(s => s.Z, opt => opt.Ignore());
AssertAllSourcePropertiesMapped();
于 2013-03-14T17:10:06.763 に答える