[英]How to map collection to collection container with Automapper?
I'm having some trouble trying to map these two classes (Control -> ControlVM) 我在尝试映射这两个类时遇到了一些麻烦(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. 我尝试使用
opt.ResolveUsing(src => new { Items = src.Fields })
但显然AutoMapper无法解析匿名类型。 Also tried extending ValueResolver
, but didn't work either. 还尝试扩展
ValueResolver
,但也没有工作。
NOTE: This VM is later used in a WebApi, and JSON.NET needs a wrapper around the collection to properly deserialize it. 注意:此VM稍后在WebApi中使用,并且JSON.NET需要围绕集合包装以正确反序列化它。 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. 注意2:我也在做
Mapper.CreateMap<Control.FieldType, ControlVM.FieldType>()
,所以问题不在那里。
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.