2016-10-16 10 views
2
私は以下の送信元と送信先のオブジェクトを持っています

に順位割り当て:私は先のコレクションオブジェクトにソースのコレクションオブジェクトをマップしようとしていますAutomapper - Destinationオブジェクト

public class Source 
{  
    public string Value1{ get; set; } 

} 

public class Destination 
{ 
    public string Value1{ get; set; } 
    public int Ranking { get; set; } 
} 

。私のソースコレクションは、このようなものです:

var source = new List<Source>(); 
source.Add(new Source(){ Value1= "test1" }); 
source.Add(new Source(){ Value1= "test2" }); 

先のオブジェクトのランキングの属性は、ソースコレクション内の項目のインデックスに対応していなければならない場合、私はマッパーを書くことができますどのように?

I.e.マッピング後、Value1 = "test1"Sourceの行き先ランキングは1となり、次は2となります。マップアクションの前後

+0

なぜこのようなことをしたいですか?それは1つの大きなコードのにおいです。 AutoMapperソリューションを探すのではなく、このコードを簡単にするようにしてください。 –

+0

私はAutomapperが提供しているものがあることを知りたかったのです。私はリストを反復して値をマップしたくなかった –

答えて

1

あなたはそれをいくつかの方法を行うことができますが、あなたは、コンバータユニットがテスト可能たい場合、私はITyperConverter<TSource, TDestination>から継承したクラスを使用してお勧めします。

変換クラス:

var sources = new List<Source>{ 
    new Source() { Value1 = "test1" }, 
    new Source() { Value1 = "test2" } 
}; 

var destinationsRanked = sources.Select(s => Mapper.Map<Source, Destination>(s, options => options.ConstructServicesUsing(
     type => new SourceToDestinationConverter((source.IndexOf(s) + 1)) 
))); 

結果がされて終わる:メソッドの呼び出し

Mapper.Initialize(config => 
{ 
     config.CreateMap<Source, Destination>().ConvertUsing<SourceToDestinationConverter>(); 
}); 
Mapper.AssertConfigurationIsValid(); 

public class SourceToDestinationConverter : ITypeConverter<Source, Destination> 
{ 
    private int currentRank; 
    public SourceToDestinationConverter(int rank) 
    { 
     currentRank = rank; 
    } 

    public Destination Convert(Source source, Destination destination, ResolutionContext context) 
    { 
     destination = new Destination 
     { 
      Value1 = source.Value1, 
      Ranking = currentRank 
     }; 
     return destination; 
    } 
} 

はマッパーの設定にあなたのクラスを設定します。

Value1 | Ranking 
test1 | 1 
test2 | 2 
1

使用(the docsを参照してください):

var source = new List<Source>(); 
source.Add(new Source() { Value1 = "test1" }); 
source.Add(new Source() { Value1 = "test2" }); 

Mapper.Initialize(config => 
{ 
    config.CreateMap<Source, Destination>(); 
}); 

var destinations = source.Select(x => Mapper.Map<Source, Destination>(x, opt => { 
    opt.AfterMap((src, dest) => dest.Ranking = source.IndexOf(x) + 1); 
})); 
関連する問題