2016-12-15 26 views
1

私は自分の複雑な型から自分のWebサービスAPIで使用される他のやや複雑な型に変換するためにAutoMapperを使用しています。多型を使用した複雑な型の自動マッピング?

namespace Source 
{ 
    public class Order 
    { 
     public int OrderID { get; set; } 
     public Client Client { get; set; } 
     ... 
    } 

    public class ExistingClient : Client 
    { 
     public int ClientID { get; set; } 
     ... 
    } 

    public class NewClient : Client 
    { 
     public string Name { get; set; } 
     ... 
    } 
} 

と私は、次のCreateMapコール(プラスいくつかのより多くを含んでいるAutoMapperプロファイルを作成した以下の

namespace Target 
{ 
    public class WebOrder 
    { 
     public int OrderID { get; set; } 
     public WebClient { get; set; } 
     ... 
    } 

    public class WebClient 
    { 
     public object Item // instance of NewWebClient or ExistingWebClient 
    } 

    public class ExistingWebClient 
    { 
     public int ClientID { get; set; } 
     ... 
    } 

    public class NewWebClient 
    { 
     public string Name { get; set; } 
     ... 
    } 
} 

にこれらを変換する必要があります。ここでは

は私のタイプがあります)

CreateMap<Source.ExistingClient, Target.ExistingWebClient>(); 
CreateMap<Source.NewClient, Target.NewWebClient>(); 
CreateMap<Source.Client, Target.WebClient>(); 

しかし、私はで多型を使用する方法に固執していますまたはResolveUsing()でItemプロパティを正しく設定できます。最後の行を各サブタイプの別のマップに置き換えるのは不十分ですが、不器用で反復的です。

CreateMap<Source.NewClient, Target.WebClient>() 
    .ForMember(d => d.Item, o => o.MapFrom(s => 
     Mapper.Map<Source.NewClient, Target.NewWebClient>(s))); 

CreateMap<Source.ExistingClient, Target.WebClient>() 
    .ForMember(d => d.Item, o => o.MapFrom(s => 
     Mapper.Map<Source.ExistingClient, Target.ExistingWebClient>(s))); 

答えて

0

これは一番きれいな方法ですかどうかわかりませんが、最終的にカスタムリゾルバクラスを使用して解決しました。

public class ClientResolver : IValueResolver<Source.Client, Target.ClientWeb, object> 
{ 
    public object Resolve(Source.Client source, Target.ClientWeb destination, object destMember, ResolutionContext context) 
    { 
     if (source is Source.NewClient) 
     { 
      return Mapper.Map<Source.NewClient, Target.NewClientWeb>(source as Source.NewClient); 
     } 
     else if (source is Source.ExistingClient) 
     { 
      return Mapper.Map<Source.ExistingClient, Target.ExistingClientWeb>(source as Source.ExistingClient); 
     } 
     return null; 
    } 
} 
関連する問題