建立在 @dtryon 的回答基础上,这个问题的难点在于没有办法将
NameValueCollection
中的内部对象映射到您的 DTO 类型。
您可以编写一个自定义转换器,从
NameValueCollection
中的项目构造
KeyValuePair<string, string>
对象。这将允许您创建一个通用转换器,利用另一个从
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));
最后,使用自定义转换器创建
NameValueCollection
和
List<MetaModel>
之间的映射。
Mapper.CreateMap<NameValueCollection, List<MetaModel>>()
.ConvertUsing<NameValueCollectionConverter<MetaModel>>();