2013-03-14 16 views
7

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

私はマッピングの例外を受け取りません。私がしたいのは、Source.Zが明示的に無視されないので、AutoMapperConfigurationExceptionがスローされるということです。現在

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

、AutoMapper が例外をスローしません:私は持っていることを明示的に例外なしで実行するようにAssertConfiguartionIsValidためにZプロパティを無視するよう

は、私はそれをしたいと思います。 Ignoreを明示的に指定しないと例外がスローされます。これどうやってするの?ここ

答えて

4

は、すべてのソース・タイプのプロパティがマッピングされていることを主張する方法であって

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

例外タイプの

プロパティ 'のInt32 Z' を投げる 'YourNamespace.Source'、

にマッピングされていませんすべてが問題ありません。

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

ソースメンバーのマッピングが 'TypeMap'に公開されていないのは残念です。 –

+0

@MikeBanteguiはあなたに完全に同意します。答えの最初の編集では、私は単に 'GetPropertyMaps()'を使いましたが、どちらのソースマッピングもここにはなかったし、ソースマッピングもTypeMapのpublicプロパティとして公開されていなかったことは驚きでした –

関連する問題