简体   繁体   中英

How to map collection to collection container with Automapper?

I'm having some trouble trying to map 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 apparently AutoMapper cannot resolve the anonymous type. Also tried extending ValueResolver , but didn't work either.

NOTE: This VM is later used in a WebApi, and JSON.NET needs a wrapper around the collection to properly deserialize it. So removing the wrapper is not a solution.

NOTE2: I'm also doing Mapper.CreateMap<Control.FieldType, ControlVM.FieldType>() , so the problem isn't there.

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's how to map the other way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM