2011-07-15 79 views
2

我遇到了一個我自動映射配置的問題,我似乎無法解決。AutoMapper問題映射實體到詞典<GUID,字符串>

我有一個聯繫類型的實體,我試圖將這些列表映射到字典。但是,映射只是沒有做任何事情。源字典保持空白。任何人都可以提供建議嗎?

下面是接觸式

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網站上的文檔非常粗略。從我所知道的,Mapper.Map中的第二個參數僅用於確定返回值應該是什麼類型,而實際上並未修改。這是因爲它允許您基於只在運行時已知類型的現有對象執行動態映射,而不是在泛型中對類型進行硬編碼。

因此,您的代碼中的問題是您沒有使用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來運行該示例。)

希望這有助於!

+0

感謝您提供的樣品mellamokb。我不敢相信我沒有遇到過這個! – WDuffy

10

這應該工作的簡化版本與以下,沒有Mapper需要...

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

尼斯加布,雖然技術上沒有回答AutoMapper問題這種情況下我認爲你的解決方案是一個更清潔的選擇 – WDuffy

0

在GitHub上AutoMapper另一種解決方案:

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

oakinger [CodePlex上]剛寫的是解決了這個小擴展方法:

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])?它需要一個字符串參數,而不是一個lambda。 – Nuzzolilo

+0

該參考資料是https://github.com/AutoMapper/AutoMapper/issues/51 – Kiquenet

相關問題