2012-02-20 34 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

相关问题