2012-02-20 32 views

回答

3

捎帶斷@dtryon's answer,這個艱難的部分是,有沒有辦法在NameValueCollection內部對象映射到DTO類型。

你可以做的一件事是寫一個custom converter,它構造KeyValuePair<string, string>對象NameValueCollection中的項目。這將允許您創建一個通用轉換器,以利用從KeyValuePair到您選擇的目標類型的另一個映射。喜歡的東西:

public class NameValueCollectionConverter<T> : ITypeConverter<NameValueCollection, List<T>> 
{ 
    public List<T> Convert(ResolutionContext ctx) 
    { 
     NameValueCollection source = ctx.SourceValue as NameValueCollection; 

     return source.Cast<string>() 
      .Select (v => MapKeyValuePair(new KeyValuePair<string, string>(v, source[v]))) 
      .ToList(); 
    } 

    private T MapKeyValuePair(KeyValuePair<string, string> source) 
    { 
     return Mapper.Map<KeyValuePair<string, string>, T>(source); 
    } 
} 

那麼你就需要從KeyValuePair<string, string>MetaModel定義的映射:

Mapper.CreateMap<KeyValuePair<string, string>, MetaModel>() 
    .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Key)) 
    .ForMember(dest => dest.Value, opt => opt.MapFrom(src => src.Value)); 

最後,創建NameValueCollectionList<MetaModel>之間的映射,使用自定義轉換器:

Mapper.CreateMap<NameValueCollection, List<MetaModel>>() 
    .ConvertUsing<NameValueCollectionConverter<MetaModel>>(); 
1

好吧,既然NameValueCollection中是如此特殊,我不認爲有這樣做的好方法。這主要是由於您無法獲得NameValueCollection中的鍵/值對象的句柄。幸運的是,映射到List<MetaModel>的代碼並不是那麼糟糕。我只想手動映射並繼續工作:

[TestMethod] 
    public void TestMethod2() 
    { 
     List<MetaModel> dest = new List<MetaModel>(); 
     NameValueCollection src = new NameValueCollection(); 

     src.Add("Key1", "Value1"); 
     src.Add("Key2", "Value2"); 
     src.Add("Key3", "Value3"); 
     src.Add("Key4", "Value4"); 
     src.Add("Key5", "Value5"); 

     foreach (var srcItem in src.AllKeys) 
     { 
      dest.Add(new MetaModel() { Name = srcItem, Value = src[srcItem] }); 
     } 

     Assert.AreEqual(5, dest.Count); 

    } 
+0

+1,雖然你可以把它包裝在一個自定義的解析器中,使它更具可重用性 – 2012-02-20 18:32:24

+0

How你會那樣做嗎? – 2012-02-20 20:12:19

相關問題