要列出的 AutoMapper DataServiceCollection<string>

AutoMapper DataServiceCollection to List<string>

我试图使用 AutoMapper 将 DataServiceCollection 映射到字符串列表并创建反向映射。关于如何将这样的专门集合映射到另一个集合有什么想法吗?

Mapper.CreateMap<DataServiceCollection<LocationCountyValue>, List<string>>();

您可以创建自定义类型转换器:

public class DataServiceCollectionToStringList : ITypeConverter<DataServiceCollection<LocationCountyValue>, List<string>> {
    public List<string> Convert(ResolutionContext context) {
        var sourceValue = (DataServiceCollection<LocationCountyValue>) context.SourceValue;

        /* Your custom mapping here. */
    }
}

然后用ConvertUsing创建地图:

Mapper.CreateMap<DataServiceCollection<LocationCountyValue>, List<string>>()
      .ConvertUsing<DataServiceCollectionToStringList>();

感谢 Thiago Sa,我创建了双向映射,如下所示:

Mapper.CreateMap<DataServiceCollection<CountyValue>, List<string>>()
    .ConvertUsing((src) => { return src.Select(c => c.Value).ToList(); });

Mapper.CreateMap<List<string>, DataServiceCollection<CountyValue>>()
    .ConvertUsing((src) =>
    {
        return new DataServiceCollection<CountyValue>(
            src.Select(c => new CountyValue() { Value = c }));
    });