2012-05-11 126 views
3

我有一些麻烦,试图将这两个类映射(控制 - > ControlVM)如何使用Automapper将集合映射到集合容器?

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,但也没有工作。

NOTE:该虚拟机稍后在WebApi中使用,并且JSON.NET需要对该集合进行封装来正确地反序列化它。所以删除包装不是一个解决方案。

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

回答

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)); 
+0

太好了!它也可以在没有最后一个'CreateMap'的情况下工作(AutoMapper总是试图映射具有相同名称的属性) – faloi

+0

@faloi:好点,我会把这个映射出去。 –

+0

你将如何执行逆映射? (ControlVM.FieldList - > IEnumerable )。 AutoMapper抛出“AutoMapper.AutoMapperConfigurationException:成员的自定义配置只支持顶级单个成员的类型。” – faloi