在 automapper 中,如何将名称值集合映射到强类型集合?
Mapper.Map<NameValueCollection, List<MetaModel>>();
public class MetaModel
{
public string Name;
public string Value;
}
最佳答案
捎带 @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));
最后,在
NameValueCollection
之间创建一个映射和 List<MetaModel>
,使用自定义转换器:Mapper.CreateMap<NameValueCollection, List<MetaModel>>()
.ConvertUsing<NameValueCollectionConverter<MetaModel>>();
关于Automapper - 将 NameValueCollection 转换为强类型集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9357497/