How to map a collection to a data collection container using Automapper?

I'm having trouble displaying these two classes (Control -> ControlVM)

    public class Control
    {
        public IEnumerable<FieldType> Fields { get; set; }

        public class FieldType
        {
            //Some properties
        }
    }


    public class ControlVM
    {
        public FieldList Fields { get; set; }

        public class FieldList
        {
            public IEnumerable<FieldType> Items { get; set; }
        }

        public class FieldType
        {
            //Properties I'd like to map from the original
        }
    }

I tried with opt.ResolveUsing(src => new { Items = src.Fields }), but AutoMapper apparently cannot resolve the anonymous type. Also tried the extension ValueResolver, but also did not work.

NOTE. . This virtual machine is later used by WebApi, and JSON.NET needs a wrapper around the collection to deserialize it. Therefore, removing the shell is not a solution.

NOTE2: I also do Mapper.CreateMap<Control.FieldType, ControlVM.FieldType>(), so there is no problem there.

+3
source share
1 answer

This works for me:

Mapper.CreateMap<Control.FieldType, ControlVM.FieldType>();

// Map between IEnumerable<Control.FieldType> and ControlVM.FieldList:
Mapper.CreateMap<IEnumerable<Control.FieldType>, ControlVM.FieldList>()
    .ForMember(dest => dest.Items, opt => opt.MapFrom(src => src));

Mapper.CreateMap<Control, ControlVM>();

Update: here is how to map another way:

Mapper.CreateMap<ControlVM.FieldType, Control.FieldType>();
Mapper.CreateMap<ControlVM, Control>()
    .ForMember(dest => dest.Fields, opt => opt.MapFrom(src => src.Fields.Items));
+4
source

All Articles