Automapper - 将 NameValueCollection 转换为强类型集合

标签 automapper

在 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/

相关文章:

c# - 如何配置 AutoMapper 在映射时不检查成员列表?

c# - 使用 DTO 和实体是否违反 DRY 原则?

c# - 使用 Automapper (.net c#) 映射到不在 Src 中的变量以便在 linq2sql 类中使用?

asp.net - 使用嵌套对象在 Linq 中将 IQueryable<Entity> 映射到 IQueryable<DTO>

c# - AutoMapper MapFrom 用于计算?

c# - 如何使用从字符串到字符串列表的自动映射器

asp.net-core - ASP.NET Core MVC 中的 AutoMapper 实现

c# - 查找并验证所有自动映射器映射

c# - AutoMapper - 将 2 个对象列表合并为 1 个列表

c# - 迁移到 AutoMapper 4.2/5.0 时,我应该在依赖注入(inject)容器中存储 IMapper 实例还是 MapperConfiguration 实例?