2011-07-15 10 views
2

私の解決していない私の自動構成の1つに問題があります。AutoMapperの問題へのエンティティのマッピング<guid、string>

私は連絡先タイプのエンティティを持っており、これらのリストを辞書にマップしようとしています。しかし、マッピングは何もしません。ソース辞書は空のままです。誰も提案を提供できますか?

以下

は、コンタクトタイプ

public class Contact 
{ 
    public Guid Id { get; set ;} 
    public string FullName { get; set; } 
} 

の簡易版である

Mapper.CreateMap<Contact, KeyValuePair<Guid, string>>() 
    .ConstructUsing(x => new KeyValuePair<Guid, string>(x.Id, x.FullName)); 

を次のように私の自動マッピングの設定は、ルックスと

var contacts = ContactRepository.GetAll(); // Returns IList<Contact> 
var options = new Dictionary<Guid, string>(); 
Mapper.Map(contacts, options); 

答えて

5

マニュアルは、AutoMapperのWebサイトで非常に概略的です。私が知ることから、Mapper.Mapの2番目のパラメータは戻り値がどんな型であるべきかを決定するためだけに使われ、実際には変更されません。これは、ジェネリックのタイプをハードコーディングするのではなく、実行時にのみタイプが分かっている既存のオブジェクトに基づいて動的マッピングを実行できるためです。

コードの問題は、最終的に変換されたオブジェクトを実際に含むMapper.Mapという戻り値を使用していないことです。ここでは、私がテストし、期待どおりに変換されたオブジェクトを正しく返すあなたのコードの修正版です。

var contacts = ContactRepository.GetAll(); 
var options = Mapper.Map(contacts, new Dictionary<Guid, string>()); 
// options should now contain the mapped version of contacts 

それだけのタイプを指定する必要がオブジェクトを構築するのではなく、一般的なバージョンを利用するために、より効率的であるが、(ここでは

var options = Mapper.Map<List<Contact>, Dictionary<Guid, string>>(contacts); 

がLinqPadで実行することができます working code sampleですサンプルを実行するには AutoMapper.dllへのアセンブリ参照が必要です。)

これが役立ちます。 GitHubのAutoMapperで

+0

ありがとうmellamokb、あなたが提供したサンプルが動作します。私はこれまでにこれに遭遇していないとは信じられない! – WDuffy

10

これは動作するはずですが、次のように私の呼び出し元のコードが見えます以下では、Mapperは必要ありませんでした。

var dictionary = contacts.ToDictionary(k => k.Id, v => v.FullName); 
+0

ニースゲイブをこのケースでは、あなたのソリューションはよりクリーンな選択肢だと思います。 – WDuffy

0

別の解決策:

https://github.com/AutoMapper/AutoMapper/issues/51

oakinger [CodePlexの]だけでこれを解決し、小さな拡張メソッドを書いた:技術的にAutoMapperの問題に答えていないが、

public static class IMappingExpressionExtensions 
{ 
public static IMappingExpression<IDictionary, TDestination> ConvertFromDictionary<TDestination>(this IMappingExpression<IDictionary, TDestination> exp, Func<string, string> propertyNameMapper) 
{ 
foreach (PropertyInfo pi in typeof(Invoice).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) 
{ 
if (!pi.CanWrite || 
pi.GetCustomAttributes(typeof(PersistentAttribute), false).Length == 0) 
{ 
continue; 
} 

string propertyName = pi.Name; 
propertyName = propertyNameMapper(propertyName); 
exp.ForMember(propertyName, cfg => cfg.MapFrom(r => r[propertyName])); 
} 
return exp; 
} 
} 

Usage: 

Mapper.CreateMap<IDictionary, MyType>() 
.ConvertFromDictionary(propName => propName) // map property names to dictionary keys 
+0

これはコンパイルされません。 PersistentAttributeは有効なオブジェクトではありません。しかし、それは問題ではありません。どのようにcfg.MapFrom(r => r [propertyName])を扱うのですか?ラムダではなく、文字列パラメータを受け取ります。 – Nuzzolilo

+0

参照はhttps://github.com/AutoMapper/AutoMapper/issues/51です – Kiquenet

関連する問題