3

我在尝试映射这两个类时遇到了一些麻烦(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>(),所以问题不存在。

4

1 回答 1

4

这对我有用:

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));
于 2012-05-11T22:32:38.553 回答