繁体   English   中英

如何使用Automapper将集合映射到集合容器?

[英]How to map collection to collection container with Automapper?

我在尝试映射这两个类时遇到了一些麻烦(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
        }
    }

我尝试使用opt.ResolveUsing(src => new { Items = src.Fields })但显然AutoMapper无法解析匿名类型。 还尝试扩展ValueResolver ,但也没有工作。

注意:此VM稍后在WebApi中使用,并且JSON.NET需要围绕集合包装以正确反序列化它。 因此删除包装器不是解决方案。

注意2:我也在做Mapper.CreateMap<Control.FieldType, ControlVM.FieldType>() ,所以问题不在那里。

这对我有用:

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

更新 :以下是如何映射其他方式:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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