2011-05-13 177 views
10

鑑於這些類,如何映射它們的字典?使用AutoMapper映射字典

public class TestClass 
{ 
    public string Name { get; set; } 
} 

public class TestClassDto 
{ 
    public string Name { get; set; } 
} 


Mapper.CreateMap<TestClass, TestClassDto>(); 
Mapper.CreateMap<Dictionary<string, TestClass>, 
        Dictionary<string, TestClassDto>>(); 

var testDict = new Dictionary<string, TestClass>(); 
var testValue = new TestClass() {Name = "value1"}; 
testDict.Add("key1", testValue); 

var mappedValue = Mapper.Map<TestClass, TestClassDto>(testValue); 

var mappedDict = Mapper.Map<Dictionary<string, TestClass>, 
          Dictionary<string, TestClassDto>>(testDict); 

映射其中之一,在這種情況下mappedValue,工作正常。

映射它們的字典最終沒有在目標對象中的條目。

我在做什麼工作?

回答

13

您遇到的問題是因爲AutoMapper正在努力映射字典的內容。你必須考慮它是什麼店 - 在這種情況下KeyValuePairs

如果試圖創建的KeyValuePair組合的映射器,你會很快制定出,你不能直接作爲Key屬性沒有一個二傳手

AutoMapper解決這個問題,但允許您使用構造函數進行映射。

/* Create the map for the base object - be explicit for good readability */ 
Mapper.CreateMap<TestClass, TestClassDto>() 
     .ForMember(x => x.Name, o => o.MapFrom(y => y.Name)); 

/* Create the map using construct using rather than ForMember */ 
Mapper.CreateMap<KeyValuePair<string, TestClass>, KeyValuePair<string, TestClassDto>>() 
     .ConstructUsing(x => new KeyValuePair<string, TestClassDto>(x.Key, 
                    x.Value.MapTo<TestClassDto>())); 

var testDict = new Dictionary<string, TestClass>(); 
var testValue = new TestClass() 
{ 
    Name = "value1" 
}; 
testDict.Add("key1", testValue); 

/* Mapped Dict will have your new KeyValuePair in there */ 
var mappedDict = Mapper.Map<Dictionary<string, TestClass>, 
Dictionary<string, TestClassDto>>(testDict); 
+0

請注意,第二個ConstructUsing位使用第一個地圖來完成它的工作。 – 2011-06-18 01:18:35