2016-08-23 3 views
-1
CreateMap<SourceType, DestinationType>() 
    .ForMember(dest => dest.Type3Property, opt => opt.MapFrom 
    (
     src => new Type3 
     { 
      OldValueType5 = src.oldValType6, 
      NewValueType5 = src.newValType6 
     } 
    ); 

Type3を作成する際に、Type6のネストされたプロパティをType5に割り当てる必要があります。 Automapperを使ってどうすればいいですか?異なるタイプのネストされたオブジェクトをマッピングするAutoMapper

+2

これを展開する必要があります。これは、タイプに関する詳細なデータと、実行したいものの例です。 – stuartd

+2

各タイプのマップを作成できませんか?そうすると、ネストされた型が自動的にマップされます。 [ネストされたマッピング](https://github.com/AutoMapper/AutoMapper/wiki/Nested-mappings)のドキュメントをチェックしてください。しかし、@stuartdが述べたように、より完全な例が役立つでしょう。 – MisterIsaak

+0

私はあなたの意見に同意しますが、InnerSource-> OtherValue(Type6)とInnerDest-> OtherValue(Type5)は異なるタイプです。 –

答えて

1

質問に完全に答えるためには、さらに完全な例が必要になるでしょう。しかし、今まで私たちに与えてきたことから、Type6からType5へのマッピングを追加する必要があると思います。

これらの「ネストされたプロパティ」のマッピングの例を次に示します。これを過去にコンソールアプリケーションにコピーして、自分で実行することができます。

class Program 
{ 
    static void Main(string[] args) 
    { 
     var config = new MapperConfiguration(cfg => 
     { 
      //The map for the outer types 
      cfg.CreateMap<SourceType, DestinationType>() 
       .ForMember(dest => dest.Type3Property, opt => opt.MapFrom(src => src.Inner)); 
      //The map for the inner types 
      cfg.CreateMap<InnerSourceType, Type3>(); 
      //The map for the nested properties in the inner types 
      cfg.CreateMap<Type6, Type5>() 
       //You only need to do this if your property names are different 
       .ForMember(dest => dest.MyType5Value, opt => opt.MapFrom(src => src.MyType6Value)); 

     }); 

     config.AssertConfigurationIsValid(); 
     var mapper = config.CreateMapper(); 

     var source = new SourceType 
     { 
      Inner = new InnerSourceType { 
       OldValue = new Type6 { MyType6Value = 15 }, 
       NewValue = new Type6 { MyType6Value = 20 } 
      } 
     }; 

     var result = mapper.Map<SourceType, DestinationType>(source); 
    } 
} 

public class SourceType 
{ 
    public InnerSourceType Inner { get; set; } 
} 

public class InnerSourceType 
{ 
    public Type6 OldValue { get; set; } 
    public Type6 NewValue { get; set; } 
} 

public class DestinationType 
{ 
    public Type3 Type3Property { get; set; } 
} 

//Inner destination 
public class Type3 
{ 
    public Type5 OldValue { get; set; } 
    public Type5 NewValue { get; set; } 
} 

public class Type5 
{ 
    public int MyType5Value { get; set; } 
} 

public class Type6 
{ 
    public int MyType6Value { get; set; } 
} 
関連する問題