2017-01-31 9 views
2

オブジェクトリストのintプロパティをList<int>にマップする必要があります。オートマップマップのプロパティ値リスト<type>からリスト<int>

私は親クラスがあります:

public class Parent 
{ 
    ... 
    public List<Location> Locations { get; set; } 
} 

Locationクラス:

public class Location 
{ 
    public int LocationId { get; set; } 
    public string Name { get; set; } 
} 

マッピングのためのデスティネーションクラス:ここ

public class Destination 
{ 
    ... 
    public List<int> Locations { get; set; } 
} 

ここ は私のクラスの構造は次のようになりますの間のマッピングを達成するために使用しようとしているコードです〜List<int>

CreateMap<Parent, Destination>() 
.ForMember(d => d.Locations, o => o.MapFrom(s => s.Locations.Select(l => l.LocationId))) 

これは機能しません。私は右やっていないよ何

AutoMapper.AutoMapperMappingException: Unable to create a map expression from Location.LocationId (System.Collections.Generic.IEnumerable`1[System.Int32]) to Destination.Locations (System.Collections.Generic.List`1[System.Int32])

任意のアイデア:私は次のエラーを取得しますか?例外として

+1

あなたの選択の最後に.ToList()を試しましたか? – JamesT

+0

良いアイデア。私はこれを試して、それを処理したようだ。ありがとう! – DCATEK

答えて

2

は言う:

AutoMapper.AutoMapperMappingException: Unable to create a map expression from Location.LocationId (System.Collections.Generic.IEnumerable1[System.Int32]) to Destination.Locations (System.Collections.Generic.List1[System.Int32])

私はあなたがリストにIEnumerableををマップしようとしているので、これが起こると信じています。 Selectの後にマップ式にToList()を追加するか、 (推奨しません) Locationsプロパティを宛先クラスのIEnumerable<int>として宣言します。

+1

これはJamesTが上記のコメントで提案したものです。これは私の問題を解決しました。ありがとう! – DCATEK

+0

クリスピックフォードが提案するように、私はLocation to intへのマッピングを追加しなければならなかったことが分かりました。それと、.ToList()は私の問題を解決しました。 – DCATEK

-1

は、あなたはそれがあなたのための残りの世話をするLocation間とintマップするために、あなたのAutoMapperの設定を変更する必要があります。

cfg.CreateMap<Location, int>().ConvertUsing(source => source.LocationId); 
cfg.CreateMap<Parent, Destination>().ForMember(dest => dest.Locations, opts => opts.MapFrom(src => src.Locations)); 

は例を操作するためのthis Gistを参照してください。

+0

@downvoter - この回答が間違っているか改善できるかを説明するケア? –

+0

投票が下がった理由はわかりません。私はあなたの最初のコード行を使って正しい答えを得なければなりませんでした。 – DCATEK

関連する問題