AutoMapper DataServiceCollection到List <string>

时间:2015-06-12 20:55:01

标签: automapper automapper-2 automapper-3

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

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

2 个答案:

答案 0 :(得分:1)

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

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>();

答案 1 :(得分:0)

感谢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 }));
    });