AutoMapper DataServiceCollection to List<string>

617 Views Asked by At

I am attempted to use AutoMapper to map a DataServiceCollection to a list of strings and also create the reverse mapping. Any ideas on how to map a specialized collection like this to another?

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

There are 2 best solutions below

0
On BEST ANSWER

Thanks to Thiago Sa I created the mapping in both directions like so:

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 }));
    });
0
On

You can create a custom type converter:

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

        /* Your custom mapping here. */
    }
}

Then create the map with ConvertUsing:

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